Re: [R] apply function across dataframe columns for non-exclusive groups

2015-10-21 Thread Jeff Newmiller
The calculation appears to be sum(a)/(sum(a)+sum(b)).

library(dplyr)
library(tidyr)
result <- (   this_df
  %>% gather( group, truth, -c(a,b) )
  %>% group_by( group, truth )
  %>% summarise( calc = sum(a)/(sum(a)+sum(b)) )
  %>% as.data.frame
  )

---
Jeff NewmillerThe .   .  Go Live...
DCN:Basics: ##.#.   ##.#.  Live Go...
  Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/BatteriesO.O#.   #.O#.  with
/Software/Embedded Controllers)   .OO#.   .OO#.  rocks...1k
--- 
Sent from my phone. Please excuse my brevity.

On October 21, 2015 1:30:46 PM GMT+02:00, Alexander Shenkin  
wrote:
>Hello all,
>
>I've been banging my head over what must be a simple solution.  I would
>
>like to apply a function across columns of a dataframe for rows grouped
>
>across different columns.  These groups are not exclusive.  See below 
>for an example.  Happy to use dplyr, data.table, or whatever.  Any 
>guidance appreciated!
>
>Thanks,
>Allie
>
>
>desired algorithm: calculate a/(a+b) for each TRUE and FALSE grouping
>of 
>columns grp1 and grp2.
>
>this_df = data.frame(a = c(1,2,3,4,5), b = c(7,8,9,10,11), grp1 = 
>c(T,T,F,F,F), grp2 = c(F,T,F,T,F))
>
>desired output (doesn't have to be exactly this format, but something 
>along these lines):
>
>grp1 T 0.166
>grp1 F 0.286
>grp2 T 0.25
>grp2 F 0.25
>
>__
>R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function across dataframe columns for non-exclusive groups

2015-10-21 Thread Alexander Shenkin

Hello all,

I've been banging my head over what must be a simple solution.  I would 
like to apply a function across columns of a dataframe for rows grouped 
across different columns.  These groups are not exclusive.  See below 
for an example.  Happy to use dplyr, data.table, or whatever.  Any 
guidance appreciated!


Thanks,
Allie


desired algorithm: calculate a/(a+b) for each TRUE and FALSE grouping of 
columns grp1 and grp2.


this_df = data.frame(a = c(1,2,3,4,5), b = c(7,8,9,10,11), grp1 = 
c(T,T,F,F,F), grp2 = c(F,T,F,T,F))


desired output (doesn't have to be exactly this format, but something 
along these lines):


grp1 T 0.166
grp1 F 0.286
grp2 T 0.25
grp2 F 0.25

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply Function to Columns

2014-10-24 Thread Rui Barradas

Hello,

Please cc the list, the odds of getting more and better answers are greater.
And you should tell us from what package do the function plot.correlog 
comes. library(what)?


As for your question, assuming you want to save your plots as PNG files, 
you could do something like the following.



fun <- function(p){
fname <- paste0("correlog", p)
png(filename = fname)
plot.correlog(...)
dev.off()
}
ddeg.correlog.list <- lapply(9:20, fun)

See the help page for ?png. It lists several other graphics file formats 
you can use.


Hope this helps,

Rui Barradas

Em 24-10-2014 08:23, Sarah escreveu:

Thank you very much, it helped a lot!

I just have another question know. I want to make plot for every
species. I just add the function « plot correlog » to the previous
function and I have now the following script:

ddeg.correlog.list <- lapply(9:20, function(p)
*plot.correlog*(correlog(plant[plant[,p]=="1", 2], plant[plant[,p]=="1",
3],
  plant[plant[,p]=="1", 4],increment=2500)))

It’s working, but I wanted to know if there is a way to save each plot.
I found that I can use the dev.off function or the ggplot function of
the package ggplot2, but I can’t figure out how to use it within the
lapply function. Do you think there is a way?

Thank you for your help!

Sarah


Le 23 oct. 2014 à 17:49, Rui Barradas mailto:ruipbarra...@sapo.pt>> a écrit :

Hello,

Yes, you can use lapply. Maybe something like the following. Note that
the result is a list with one member per species. (Untested).

ddeg.correlog.list <- lapply(9:11, function(p)
correlog(plant[plant[,p]=="1", 2], plant[plant[,p]=="1", 3],
plant[plant[,p]=="1", 4]))


Hope this helps,

Rui Barradas

Em 23-10-2014 16:06, Sarah escreveu:

Hello List,

I have a database which consist of 912 plots. For each plot, I have
the presence/absence information of 260 species of plants and also 5
different environmental variables (ddeg, mind, srad, slp, topo).

The dataframe looks like this:

  Plot_NumberX Y ddeg mind   srad slp topo Galium_mollugo
Gentiana_nivalis
11 557747.6 149726.8 2598 -625 236363   8  176  0
   0
22 572499.4 145503.5 2178 -176 161970  14 -137  0
   0
33 579100.4 151800.4 1208  632 267572  33  129  0
   0
44 581301.7 150300.1 1645   83 246633  15  -70  0
   0
55 579838.7 124770.9 1102 1637 158300   2 -231  0
   0
66 577011.1 121328.6  731 2223 180286  41   70  0
   0

Now, what I wanted to do is to calculate spatial autocorrelation of
each environmental variable for each species, but only for the plots
where the species is present.

I will use the correlog function of the package ncf (doesn’t really
matter). The correlog function work with an argument X which is the
longitude, an argument Y which is the latitude and an argument Z
which is the variable you want to test for autocorrelation (in my
case, the different environmental variables).

So, for the first species I have the following script:

ddeg.correlog.9<-correlog(plant[plant[,9]=="1", 2],
plant[plant[,9]=="1", 3], plant[plant[,9]=="1", 4])

X = plant[plant[,9]=="1", 2] —>  only the X coordinate where my
species 9 is present
Y = plant[plant[,9]=="1", 3] —>  only the Y coordinate where my
species 9 is present
Z = plant[plant[,9]=="1", 4] —>  only the value of the environmental
variable where my species 9 is present

plant: dataframe
9: column corresponding to the first species
2: column corresponding to the X coordinate
3: column correspondind to the Y coordinate
4: column corresponding to the first environmental variable

So my question is: how do I repeat this script for every species
(basically, I just have to change the number « 9 » into 10, 11 and so
on) ?

I try to write a function but I’m new in R and didn’t manage to do
it. I was also considering to use the function « lapply », but I
don’t think I can use it in this case, isn’t it?

Thank you very much for your help !

Sarah
__
R-help@r-project.org  mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.





__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply Function to Columns

2014-10-24 Thread Sarah

> Le 24 oct. 2014 à 09:23, Sarah  a écrit :
> 
> Thank you very much, it helped a lot!
> 
> I just have another question know. I want to make plot for every species. I 
> just add the function « plot correlog » to the previous function and I have 
> now the following script: 
> 
> ddeg.correlog.list <- lapply(9:20, function(p)
>   plot.correlog(correlog(plant[plant[,p]=="1", 2], plant[plant[,p]=="1", 3], 
>  plant[plant[,p]=="1", 4],increment=2500)))
> 
> It’s working, but I wanted to know if there is a way to save each plot. I 
> found that I can use the dev.off function or the ggplot function of the 
> package ggplot2, but I can’t figure out how to use it within the lapply 
> function. Do you think there is a way?
> 
> Thank you for your help!
> 
> Sarah
> 
>> Le 23 oct. 2014 à 17:49, Rui Barradas > > a écrit :
>> 
>> Hello,
>> 
>> Yes, you can use lapply. Maybe something like the following. Note that the 
>> result is a list with one member per species. (Untested).
>> 
>> ddeg.correlog.list <- lapply(9:11, function(p)
>>  correlog(plant[plant[,p]=="1", 2], plant[plant[,p]=="1", 3], 
>> plant[plant[,p]=="1", 4]))
>> 
>> 
>> Hope this helps,
>> 
>> Rui Barradas
>> 
>> Em 23-10-2014 16:06, Sarah escreveu:
>>> Hello List,
>>> 
>>> I have a database which consist of 912 plots. For each plot, I have the 
>>> presence/absence information of 260 species of plants and also 5 different 
>>> environmental variables (ddeg, mind, srad, slp, topo).
>>> 
>>> The dataframe looks like this:
>>> 
>>>   Plot_NumberX   Y  ddeg mind   srad slp topo 
>>> Galium_mollugo Gentiana_nivalis
>>> 11  557747.6 149726.8 2598 -625 236363   8  176 
>>>  00
>>> 22  572499.4 145503.5 2178 -176 161970  14 -137 
>>>  00
>>> 33  579100.4 151800.4 1208  632 267572  33  129 
>>>  00
>>> 44  581301.7 150300.1 1645   83 246633  15  -70 
>>>  00
>>> 55  579838.7 124770.9 1102 1637 158300   2 -231 
>>>  00
>>> 66  577011.1 121328.6  731 2223 180286  41   70 
>>>  00
>>> 
>>> Now, what I wanted to do is to calculate spatial autocorrelation of each 
>>> environmental variable for each species, but only for the plots where the 
>>> species is present.
>>> 
>>> I will use the correlog function of the package ncf (doesn’t really 
>>> matter). The correlog function work with an argument X which is the 
>>> longitude, an argument Y which is the latitude and an argument Z which is 
>>> the variable you want to test for autocorrelation (in my case, the 
>>> different environmental variables).
>>> 
>>> So, for the first species I have the following script:
>>> 
>>> ddeg.correlog.9<-correlog(plant[plant[,9]=="1", 2], plant[plant[,9]=="1", 
>>> 3], plant[plant[,9]=="1", 4])
>>> 
>>> X = plant[plant[,9]=="1", 2] —>  only the X coordinate where my species 9 
>>> is present
>>> Y = plant[plant[,9]=="1", 3] —>  only the Y coordinate where my species 9 
>>> is present
>>> Z = plant[plant[,9]=="1", 4] —>  only the value of the environmental 
>>> variable where my species 9 is present
>>> 
>>> plant: dataframe
>>> 9: column corresponding to the first species
>>> 2: column corresponding to the X coordinate
>>> 3: column correspondind to the Y coordinate
>>> 4: column corresponding to the first environmental variable
>>> 
>>> So my question is: how do I repeat this script for every species 
>>> (basically, I just have to change the number « 9 » into 10, 11 and so on) ?
>>> 
>>> I try to write a function but I’m new in R and didn’t manage to do it. I 
>>> was also considering to use the function « lapply », but I don’t think I 
>>> can use it in this case, isn’t it?
>>> 
>>> Thank you very much for your help !
>>> 
>>> Sarah
>>> __
>>> R-help@r-project.org  mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help 
>>> 
>>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>>> and provide commented, minimal, self-contained, reproducible code.
>>> 
> 


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply Function to Columns

2014-10-23 Thread Rui Barradas

Hello,

Yes, you can use lapply. Maybe something like the following. Note that 
the result is a list with one member per species. (Untested).


ddeg.correlog.list <- lapply(9:11, function(p)
	correlog(plant[plant[,p]=="1", 2], plant[plant[,p]=="1", 3], 
plant[plant[,p]=="1", 4]))



Hope this helps,

Rui Barradas

Em 23-10-2014 16:06, Sarah escreveu:

Hello List,

I have a database which consist of 912 plots. For each plot, I have the 
presence/absence information of 260 species of plants and also 5 different 
environmental variables (ddeg, mind, srad, slp, topo).

The dataframe looks like this:

   Plot_NumberX  Y  ddeg mind   srad slp topo 
Galium_mollugo Gentiana_nivalis
11  557747.6 149726.8 2598 -625 236363   8  176 
 00
22  572499.4 145503.5 2178 -176 161970  14 -137 
 00
33  579100.4 151800.4 1208  632 267572  33  129 
 00
44  581301.7 150300.1 1645   83 246633  15  -70 
 00
55  579838.7 124770.9 1102 1637 158300   2 -231 
 00
66  577011.1 121328.6  731 2223 180286  41   70 
 00

Now, what I wanted to do is to calculate spatial autocorrelation of each 
environmental variable for each species, but only for the plots where the 
species is present.

I will use the correlog function of the package ncf (doesn’t really matter). 
The correlog function work with an argument X which is the longitude, an 
argument Y which is the latitude and an argument Z which is the variable you 
want to test for autocorrelation (in my case, the different environmental 
variables).

So, for the first species I have the following script:

ddeg.correlog.9<-correlog(plant[plant[,9]=="1", 2], plant[plant[,9]=="1", 3], 
plant[plant[,9]=="1", 4])

X = plant[plant[,9]=="1", 2] —>  only the X coordinate where my species 9 is 
present
Y = plant[plant[,9]=="1", 3] —>  only the Y coordinate where my species 9 is 
present
Z = plant[plant[,9]=="1", 4] —>  only the value of the environmental variable 
where my species 9 is present

plant: dataframe
9: column corresponding to the first species
2: column corresponding to the X coordinate
3: column correspondind to the Y coordinate
4: column corresponding to the first environmental variable

So my question is: how do I repeat this script for every species (basically, I 
just have to change the number « 9 » into 10, 11 and so on) ?

I try to write a function but I’m new in R and didn’t manage to do it. I was 
also considering to use the function « lapply », but I don’t think I can use it 
in this case, isn’t it?

Thank you very much for your help !

Sarah
__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply Function to Columns

2014-10-23 Thread Sarah
Hello List, 

I have a database which consist of 912 plots. For each plot, I have the 
presence/absence information of 260 species of plants and also 5 different 
environmental variables (ddeg, mind, srad, slp, topo).

The dataframe looks like this: 

  Plot_NumberX   Y  ddeg mind   srad slp topo 
Galium_mollugo Gentiana_nivalis
11  557747.6 149726.8 2598 -625 236363   8  176 
 00
22  572499.4 145503.5 2178 -176 161970  14 -137 
 00
33  579100.4 151800.4 1208  632 267572  33  129 
 00
44  581301.7 150300.1 1645   83 246633  15  -70 
 00
55  579838.7 124770.9 1102 1637 158300   2 -231 
 00
66  577011.1 121328.6  731 2223 180286  41   70 
 00

Now, what I wanted to do is to calculate spatial autocorrelation of each 
environmental variable for each species, but only for the plots where the 
species is present. 

I will use the correlog function of the package ncf (doesn’t really matter). 
The correlog function work with an argument X which is the longitude, an 
argument Y which is the latitude and an argument Z which is the variable you 
want to test for autocorrelation (in my case, the different environmental 
variables). 

So, for the first species I have the following script:

ddeg.correlog.9<-correlog(plant[plant[,9]=="1", 2], plant[plant[,9]=="1", 3], 
plant[plant[,9]=="1", 4]) 

X = plant[plant[,9]=="1", 2] —>  only the X coordinate where my species 9 is 
present
Y = plant[plant[,9]=="1", 3] —>  only the Y coordinate where my species 9 is 
present
Z = plant[plant[,9]=="1", 4] —>  only the value of the environmental variable 
where my species 9 is present

plant: dataframe
9: column corresponding to the first species
2: column corresponding to the X coordinate
3: column correspondind to the Y coordinate
4: column corresponding to the first environmental variable

So my question is: how do I repeat this script for every species (basically, I 
just have to change the number « 9 » into 10, 11 and so on) ?

I try to write a function but I’m new in R and didn’t manage to do it. I was 
also considering to use the function « lapply », but I don’t think I can use it 
in this case, isn’t it? 

Thank you very much for your help !

Sarah
__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to multiple list arguments

2014-10-14 Thread Rui Barradas

Hello,

Have you tried

mapply(f, list_df, list_par, MoreArgs = list(z = fix), SIMPLIFY = FALSE)

?


Hope this helps,

Rui Barradas

Em 14-10-2014 19:42, Carlos Nasher escreveu:

Hi R helpers,

I'm struggling how to apply a function to multiple lists. My function uses
a dataframe, a list of parameters and a fixed value as arguments. Now I
want to apply that function to several dataframes contained in list, with
several lists of parameters (also contained in a list) and the fixed value.
Here's an example:


#

fix <- 2 # fixed value

x <- c(1,2,3)
y <- c(4,5,6)

df_1 <- data.frame(x,y) # first dataframe
df_2 <- 2*df_1 # second dataframe

list_df <- list(df_1,df_2) # list containing dataframes

par_1 <- list(a=5,b=10) # first list of parameters
par_2 <- list(a=6,b=11) # second list of parameters

list_par <- list(par_1,par_2) # list of lists of parameters

f <- function(data,params,z){
   res <- (data$x*params$a+data$y*params$b)*z
   return(res)
}

res_1 <- f(data = df_1, params = par_1, z = fix) # result of applying
function to first dataframe and first list of parameters
res_2 <- f(data = df_2, params = par_2, z = fix) # result of applying
function to second dataframe and second list of parameters

#

I got the list of dataframes and parameters from a former use of lapply. I
was hoping to get the desired results (res_1, res_2) again in a list. I
tried mapply, but I don't get it running. Can anybody help?

Thanks and best regards,
Carlos





__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function to multiple list arguments

2014-10-14 Thread Carlos Nasher
Hi R helpers,

I'm struggling how to apply a function to multiple lists. My function uses
a dataframe, a list of parameters and a fixed value as arguments. Now I
want to apply that function to several dataframes contained in list, with
several lists of parameters (also contained in a list) and the fixed value.
Here's an example:


#

fix <- 2 # fixed value

x <- c(1,2,3)
y <- c(4,5,6)

df_1 <- data.frame(x,y) # first dataframe
df_2 <- 2*df_1 # second dataframe

list_df <- list(df_1,df_2) # list containing dataframes

par_1 <- list(a=5,b=10) # first list of parameters
par_2 <- list(a=6,b=11) # second list of parameters

list_par <- list(par_1,par_2) # list of lists of parameters

f <- function(data,params,z){
  res <- (data$x*params$a+data$y*params$b)*z
  return(res)
}

res_1 <- f(data = df_1, params = par_1, z = fix) # result of applying
function to first dataframe and first list of parameters
res_2 <- f(data = df_2, params = par_2, z = fix) # result of applying
function to second dataframe and second list of parameters

#

I got the list of dataframes and parameters from a former use of lapply. I
was hoping to get the desired results (res_1, res_2) again in a list. I
tried mapply, but I don't get it running. Can anybody help?

Thanks and best regards,
Carlos



-- 
-
Carlos Nasher
Buchenstr. 12
22299 Hamburg

tel:+49 (0)40 67952962
mobil:+49 (0)175 9386725
mail:  carlos.nas...@gmail.com

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to one specific column / Alternative to for loop

2013-11-17 Thread Stageexp

Hi,
Try:
indx <- grep("Test",test_df[,1])  ##assuming that there is some pattern
 res <- within(test_df[-indx,],titel <- rep(test_df$titel[indx],
diff(c(indx,nrow(test_df)+1))-1))

## If you need to change the class

res[] <- lapply(res,function(x) if(any(grepl("[[:alpha:]]",x)))
as.character(x) else as.numeric(as.character(x)))


##Using data.frame(cbind()), etc. creates 


A.K.


This option worked great for me! I knew there was a nicer and much faster
way to solve this. One thing I already learned about R: Never use for-loops,
there is always a better way :-)



--
View this message in context: 
http://r.789695.n4.nabble.com/Apply-function-to-one-specific-column-Alternative-to-for-loop-tp4680566p4680621.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to one specific column / Alternative to for loop

2013-11-16 Thread arun
Hi,
Try:
indx <- grep("Test",test_df[,1])  ##assuming that there is some pattern
 res <- within(test_df[-indx,],titel <- rep(test_df$titel[indx], 
diff(c(indx,nrow(test_df)+1))-1))

## If you need to change the class

res[] <- lapply(res,function(x) if(any(grepl("[[:alpha:]]",x))) as.character(x) 
else as.numeric(as.character(x)))


##Using data.frame(cbind()), etc. creates 


A.K.




On Saturday, November 16, 2013 11:14 AM, Stageexp  wrote:
Hi guys, I am a total newbie to R, so I hope this isn't a totally dumb
question. I have a dataframe with a title in one row and the corresponding
values in the next rows. Let's take this example: 

test_df <- data.frame(cbind(titel = "", x = 4:5, y = 1:2))
test_df = rbind(cbind(titel="1.Test", x="", y=""), test_df,
cbind(titel="2.Test", x="", y=""), test_df, cbind(titel="3.Test", x="",
y=""), test_df)

test_df
   titel x y
1 1.Test    
2        4 1
3        5 2
4 2.Test    
5        4 1
6        5 2
7 3.Test    
8        4 1
9        5 2

What I want to have is:
   titel x y
2 1.Test 4 1
3 1.Test 5 2
5 2.Test 4 1
6 2.Test 5 2
8 3.Test 4 1
9 3.Test 5 2

In my example, the title is in every third line, but in my real data there
is no pattern. Each title has at least one line but can have x lines.

I was able to solve my problem in a for loop with the following code:
test_df$titel <- as.character(test_df$titel)
for (i in 1:nrow(test_df))
{
  if (nchar(test_df$titel[i])==0){
    test_df$titel[i]=test_df$titel[i-1]
  }
}
test_df <- subset(test_df,test_df$x!="")


The problem is, I have a lot of data and the for loop is obviously very
slow. Is there a more elegant way to achieve the same? I think I have to use
the apply function, but I don't know how to use it with just one column.




--
View this message in context: 
http://r.789695.n4.nabble.com/Apply-function-to-one-specific-column-Alternative-to-for-loop-tp4680566.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to one specific column / Alternative to for loop

2013-11-16 Thread umair durrani
This might be of some use : 
http://nsaunders.wordpress.com/2010/08/20/a-brief-introduction-to-apply-in-r/

Umair Durrani

email: umairdurr...@outlook.com


> Date: Sat, 16 Nov 2013 07:30:29 -0800
> From: ron...@gmx.net
> To: r-help@r-project.org
> Subject: [R] Apply function to one specific column / Alternative to for loop
> 
> Hi guys, I am a total newbie to R, so I hope this isn't a totally dumb
> question. I have a dataframe with a title in one row and the corresponding
> values in the next rows. Let's take this example: 
> 
> test_df <- data.frame(cbind(titel = "", x = 4:5, y = 1:2))
> test_df = rbind(cbind(titel="1.Test", x="", y=""), test_df,
> cbind(titel="2.Test", x="", y=""), test_df, cbind(titel="3.Test", x="",
> y=""), test_df)
> 
> test_df
>titel x y
> 1 1.Test
> 24 1
> 35 2
> 4 2.Test
> 54 1
> 65 2
> 7 3.Test
> 84 1
> 95 2
> 
> What I want to have is:
>titel x y
> 2 1.Test 4 1
> 3 1.Test 5 2
> 5 2.Test 4 1
> 6 2.Test 5 2
> 8 3.Test 4 1
> 9 3.Test 5 2
> 
> In my example, the title is in every third line, but in my real data there
> is no pattern. Each title has at least one line but can have x lines.
> 
> I was able to solve my problem in a for loop with the following code:
> test_df$titel <- as.character(test_df$titel)
> for (i in 1:nrow(test_df))
> {
>   if (nchar(test_df$titel[i])==0){
> test_df$titel[i]=test_df$titel[i-1]
>   }
> }
> test_df <- subset(test_df,test_df$x!="")
> 
> 
> The problem is, I have a lot of data and the for loop is obviously very
> slow. Is there a more elegant way to achieve the same? I think I have to use
> the apply function, but I don't know how to use it with just one column.
> 
> 
> 
> 
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/Apply-function-to-one-specific-column-Alternative-to-for-loop-tp4680566.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
  
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply function to one specific column / Alternative to for loop

2013-11-16 Thread Stageexp
Hi guys, I am a total newbie to R, so I hope this isn't a totally dumb
question. I have a dataframe with a title in one row and the corresponding
values in the next rows. Let's take this example: 

test_df <- data.frame(cbind(titel = "", x = 4:5, y = 1:2))
test_df = rbind(cbind(titel="1.Test", x="", y=""), test_df,
cbind(titel="2.Test", x="", y=""), test_df, cbind(titel="3.Test", x="",
y=""), test_df)

test_df
   titel x y
1 1.Test
24 1
35 2
4 2.Test
54 1
65 2
7 3.Test
84 1
95 2

What I want to have is:
   titel x y
2 1.Test 4 1
3 1.Test 5 2
5 2.Test 4 1
6 2.Test 5 2
8 3.Test 4 1
9 3.Test 5 2

In my example, the title is in every third line, but in my real data there
is no pattern. Each title has at least one line but can have x lines.

I was able to solve my problem in a for loop with the following code:
test_df$titel <- as.character(test_df$titel)
for (i in 1:nrow(test_df))
{
  if (nchar(test_df$titel[i])==0){
test_df$titel[i]=test_df$titel[i-1]
  }
}
test_df <- subset(test_df,test_df$x!="")


The problem is, I have a lot of data and the for loop is obviously very
slow. Is there a more elegant way to achieve the same? I think I have to use
the apply function, but I don't know how to use it with just one column.




--
View this message in context: 
http://r.789695.n4.nabble.com/Apply-function-to-one-specific-column-Alternative-to-for-loop-tp4680566.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 20 rows between pairs of columns in a matrix

2013-11-11 Thread arun






HI,


set.seed(25)
dat1 <- 
as.data.frame(matrix(sample(c("A","T","G","C"),46482*56,replace=TRUE),ncol=56,nrow=46482),stringsAsFactors=FALSE)
 lst1 <- split(dat1,as.character(gl(nrow(dat1),20,nrow(dat1
res <- lapply(lst1,function(x) sapply(x[,1:8],function(y) sapply(x[,9:56], 
function(z) sum(y==z)/20)))

 length(res)
#[1] 2325  ### check here
 dim(res[[1]])
#[1] 48  8

A.K.



Hi all, I have a set of genetic SNP data that looks like 

Founder1 Founder2 Founder3 Founder4 Founder5 Founder6 Founder7 Founder8 Sample1 
Sample2 Sample3 Sample... 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 

The size of the matrix is 56 columns by 46482 rows. I need to 
first bin the matrix by every 20 rows, then compare each of the first 8 
columns (founders) to each columns 9-56, and divide the total number of 
matching letters/alleles by the total number of rows (20). Ultimately I 
need 48 8 column by 2342 row matrices, which are essentially similarity 
matrices. I have tried to extract each pair separately by something like 

"length(cbind(odd[,9],odd[,1])[cbind(odd[,9],cbind(odd[,9],odd[,1])[,1])[,1]=="T"
& cbind(odd[,9],odd[,1])[,2]=="T",])/nrow(cbind(odd[,9],odd[,1]))" 

but this is no where near efficient, and I do not know of a 
faster way of applying the function to every 20 rows and across multiple
pairs. 

In the example given above, if the rows were all identical like 
shown across 20 rows, then the first row of the matrix for Sample1 would
be 

1 1 1 0 0 0 0

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 20 rows between pairs of columns in a matrix

2013-11-11 Thread arun


Hi,
May be this what you wanted.
res2 <- lapply(row.names(res[[1]]),function(x) 
do.call(rbind,lapply(res,function(y) y[match(x, row.names(y)),])))
 length(res2)
#[1] 48
 dim(res2[[1]])
#[1] 2325    8

A.K.


On Monday, November 11, 2013 10:20 PM, Yu-yu Ren  wrote:

Thank you so much for that script, it works great. One additional request; how 
can I go about binding each of the 2325 matrices for each sample, resulting in 
48 matrices of 8 column by 2325 row?




On Mon, Nov 11, 2013 at 10:02 PM, arun  wrote:


>
>Hi,
>I already sent a reply to R-help.  I am not sure about the "2342".
>
>set.seed(25)
>dat1 <- 
>as.data.frame(matrix(sample(c("A","T","G","C"),46482*56,replace=TRUE),ncol=56,nrow=46482),stringsAsFactors=FALSE)
> lst1 <- split(dat1,as.character(gl(nrow(dat1),20,nrow(dat1
>res <- lapply(lst1,function(x) sapply(x[,1:8],function(y) sapply(x[,9:56], 
>function(z) sum(y==z)/20)))
>
> length(res)
>#[1] 2325  ### check here
> dim(res[[1]])
>#[1] 48  8
>
>A.K.
>
>
>
>
>On Monday, November 11, 2013 10:00 PM, Yu-yu Ren  wrote:
>
>Thank you, I have uploaded several example files, with intermediate outputs of 
>what I have done and the logic flow.
>
>
>
>
>On Mon, Nov 11, 2013 at 9:37 PM,  wrote:
>
>
>>Hi,
>>
>>Comparing the first 8 columns separately with 9-56 columns is not clear.  
>>Also, please provide a reproducible example (using ?dput) for others to work 
>>on.
>>
>>A.K.
>>
>>Hi all, I have a set of genetic SNP data that looks like
>>
>>Founder1 Founder2 Founder3 Founder4 Founder5 Founder6 Founder7 Founder8
>>Sample1 Sample2 Sample3 Sample...
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>A A A T T T T T A T A T
>>
>>The size of the matrix is 56 columns by 46482 rows. I need to first bin the
>>matrix by every 20 rows, then compare each of the first 8 columns (founders)
>>to each columns 9-56, and divide the total number of matching
>>letters/alleles by the total number of rows (20). Ultimately I need 48 8
>>column by 2342 row matrices, which are essentially similarity matrices. I
>>have tried to extract each pair separately by something like
>>
>>"length(cbind(odd[,9],odd[,1])[cbind(odd[,9],cbind(odd[,9],odd[,1])[,1])[,1]=="T"
>>& cbind(odd[,9],odd[,1])[,2]=="T",])/nrow(cbind(odd[,9],odd[,1]))"
>>
>>but this is no where near efficient, and I do not know of a faster way of
>>applying the function to every 20 rows and across multiple pairs.
>>
>>In the example given above, if the rows were all identical like shown across
>>20 rows, then the first row of the matrix for Sample1 would be
>>
>>1 1 1 0 0 0 0
>>
>>
>>Quoted from:
>>http://r.789695.n4.nabble.com/Apply-function-to-every-20-rows-between-pairs-of-columns-in-a-matrix-tp4680272.html
>>
>>
>>_
>>Sent from http://r.789695.n4.nabble.com
>>
>>
>

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 20 rows between pairs of columns in a matrix

2013-11-11 Thread arun
HI,

It's not very clear.
set.seed(25)
dat1 <- 
as.data.frame(matrix(sample(c("A","T","G","C"),46482*56,replace=TRUE),ncol=56,nrow=46482),stringsAsFactors=FALSE)
 lst1 <- split(dat1,as.character(gl(nrow(dat1),20,nrow(dat1
res <- lapply(lst1,function(x) sapply(x[,1:8],function(y) sapply(x[,9:56], 
function(z) sum(y==z)/20)))

 length(res)
#[1] 2325  ### check here
 dim(res[[1]])
#[1] 48  8

A.K.



Hi all, I have a set of genetic SNP data that looks like 

Founder1 Founder2 Founder3 Founder4 Founder5 Founder6 Founder7 Founder8 Sample1 
Sample2 Sample3 Sample... 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 
A A A T T T T T A T A T 

The size of the matrix is 56 columns by 46482 rows. I need to 
first bin the matrix by every 20 rows, then compare each of the first 8 
columns (founders) to each columns 9-56, and divide the total number of 
matching letters/alleles by the total number of rows (20). Ultimately I 
need 48 8 column by 2342 row matrices, which are essentially similarity 
matrices. I have tried to extract each pair separately by something like 

"length(cbind(odd[,9],odd[,1])[cbind(odd[,9],cbind(odd[,9],odd[,1])[,1])[,1]=="T"
 & cbind(odd[,9],odd[,1])[,2]=="T",])/nrow(cbind(odd[,9],odd[,1]))" 

but this is no where near efficient, and I do not know of a 
faster way of applying the function to every 20 rows and across multiple
 pairs. 

In the example given above, if the rows were all identical like 
shown across 20 rows, then the first row of the matrix for Sample1 would
 be 

1 1 1 0 0 0 0

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to do pairwise calculation

2013-09-30 Thread arun
Hi,
Not sure if this helps.

#example dataset
set.seed(24)
 mat1<-matrix(sample(1:50,20*20,replace=TRUE),ncol=20)
  set.seed(49)
 colnames(mat1)<- sample(rep(LETTERS[1:4],5),20)
 rownames(mat1)<- colnames(mat1)

mat2<-combn(LETTERS[1:4],2)
res<- sapply(split(mat2,col(mat2)),function(x){ x1<-mat1[rownames(mat1)%in% 
x[1],colnames(mat1)%in%x[1]]; x2<- mat1[rownames(mat1)%in% 
x[2],colnames(mat1)%in% x[2]];avecor(x1,x2)})
names(res)<- apply(mat2,2,paste,collapse="")
res
#   AB    AC    AD    BC    BD    CD 
#0.4806725 0.4505996 0.6160342 0.5567617 0.3721136 0.4480448 

A.K.




- Original Message -
From: Amanda Li 
To: r-help@r-project.org
Cc: 
Sent: Monday, September 30, 2013 10:55 AM
Subject: [R] Apply function to do pairwise calculation

Hello,

I want to do pairwise calculation, but I am not sure how to do so.

i.e. I have a correlation matrix M 200*200. Namely colnames(M)=rownames(M).
In addition, colnames(M) is one of A, B, C, D. I want to first sort the
matrix M into 16 modules according to colnames and rownames, and then apply:
avecor <- function(x,y) {
z <- (sum(cor(x,y)*cor(x,y))/length(cor(x,y)))^0.5
return(z)
}

So as to calculate the average correlation between A,B; A,C; A,D; B,C; B,D;
C,D.

Thanks in advance for your help!

Best,
Amanda

    [[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to do pairwise calculation

2013-09-30 Thread Adams, Jean
Amanda,

If I understand what you're trying to do, this example might help you.

M <- structure(c(0.66, 0.05, -0.93, -0.61, 0.65, -0.25, 0.23, -0.89,
 0.37, 0.38, -0.91, 0.91, -0.05, -0.65, -0.94, 0.73, -0.88, 0.25,
0.04, -0.89, -0.47, -0.46, 0.86, -0.29, 0.92, 0.22, 0.77, -0.98,
 -0.56, 0.11, 0.35, -0.49, 0.48, 0.42, -0.28, 0.16, 0.2, 0.61,
0.7, 0.94, 0.89, 0.46, 0.93, 0.36, -0.95, -0.01, 0.27, 0.73,
 -0.17, -0.93, 0.36, 0.78, 0.02, -0.8, -0.57, -0.03, -0.81, -0.74,
0.16, 0.52, 0.65, -0.45, 0.46, -0.68, -0.85, 0.74, 0.77, -0.39,
 0.03, 0.93, -0.23, -0.91, -0.14, 0.77, -0.36, 0.43, -0.5, 0.5,
-0.68, -0.6, 0.12, -0.18, 0.16, -0.38, -0.18, -0.59, -0.3, -0.14,
 0.53, -0.53, -0.56, 0.14, -0.54, 0.93, 0.54, 0.03, 0.06, 0.14,
0.97, -0.09), .Dim = c(10L, 10L), .Dimnames = list(c("D", "C",
 "D", "C", "B", "A", "C", "A", "C", "B"), c("D", "C", "D", "C",
 "B", "A", "C", "A", "C", "B")))

meanM <- data.frame(row=NA, col=NA, mean=NA)

count <- 0
for(i in 1:(ng-1)) {
for(j in (i+1):ng) {
count <- count + 1
meanM[count, "row"] <- groups[i]
 meanM[count, "col"] <- groups[j]
meanM[count, "mean"] <- mean(M[dimnames(M)[[1]]==groups[i],
dimnames(M)[[2]]==groups[j]])
 }}

Jean




On Mon, Sep 30, 2013 at 9:55 AM, Amanda Li  wrote:

> Hello,
>
> I want to do pairwise calculation, but I am not sure how to do so.
>
> i.e. I have a correlation matrix M 200*200. Namely colnames(M)=rownames(M).
> In addition, colnames(M) is one of A, B, C, D. I want to first sort the
> matrix M into 16 modules according to colnames and rownames, and then
> apply:
> avecor <- function(x,y) {
> z <- (sum(cor(x,y)*cor(x,y))/length(cor(x,y)))^0.5
> return(z)
> }
>
> So as to calculate the average correlation between A,B; A,C; A,D; B,C; B,D;
> C,D.
>
> Thanks in advance for your help!
>
> Best,
> Amanda
>
> [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply function to do pairwise calculation

2013-09-30 Thread Amanda Li
Hello,

I want to do pairwise calculation, but I am not sure how to do so.

i.e. I have a correlation matrix M 200*200. Namely colnames(M)=rownames(M).
In addition, colnames(M) is one of A, B, C, D. I want to first sort the
matrix M into 16 modules according to colnames and rownames, and then apply:
avecor <- function(x,y) {
z <- (sum(cor(x,y)*cor(x,y))/length(cor(x,y)))^0.5
return(z)
}

So as to calculate the average correlation between A,B; A,C; A,D; B,C; B,D;
C,D.

Thanks in advance for your help!

Best,
Amanda

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function within different groups

2013-05-23 Thread arun
Using the previous solution:
dat3<-mutate(dat1,f_myvar=ddply(dat1,.(group),summarize,f_myvar=mifunc(myvar))[,2])
identical(dat2,dat3)
#[1] TRUE
A.K.



- Original Message -
From: arun 
To: Estefanía Gómez Galimberti 
Cc: R help 
Sent: Thursday, May 23, 2013 1:01 PM
Subject: Re: [R] apply function within different groups

Hi,
No problem.
Try:

dat2<-within(dat1,f_myvar<-ave(myvar,group,FUN=mifunc))
 dat2
#   group var1 var2 myvar f_myvar
#1 group1    1    a   100  NA
#2 group2    2    b   200 299
#3 group2   34    c   300 300
#4 group3    5    d   400 499
#5 group3    6    e   500 500
#6 group4    7    f   600  NA
A.K.



From: Estefanía Gómez Galimberti 
To: arun  
Cc: R help  
Sent: Thursday, May 23, 2013 12:08 PM
Subject: Re: [R] apply function within different groups



Thanks a lot!!! It works perkectly!
Just one thing, is there a way to preserve my original data frame so i don´t 
need to join both tables? I could do it with rbind but my original data frame 
is not in order, so
Thanks again!



From: arun 
To: Estefanía Gómez Galimberti  
Cc: R help  
Sent: Thursday, May 23, 2013 12:48 PM
Subject: Re: [R] apply function within different groups


Hi,

May be this helps:
dat1<- read.table(text="
group var1 var2 myvar
group1 1 a 100
group2 2 b 200
group2 34 c 300
group3 5 d 400
group3 6 e 500
group4 7 f 600
",sep="",header=TRUE,stringsAsFactors=FALSE)

library(plyr)
ddply(dat1,.(group),summarize, f_myvar=mifunc(myvar)) 
#   group f_myvar
#1 group1  NA
#2
group2 299
#3 group2 300
#4 group3 499
#5 group3 500
#6 group4  NA
A.K.



- Original Message -
From: Estefanía Gómez Galimberti 
To: r help help 
Cc: 
Sent: Thursday, May 23, 2013 11:30 AM
Subject: [R] apply function within different groups



Hi,

I have a very big data frame and I would like to apply a function to one of the 
columns within different groups  and obtain another dataframe
My data frame is like this:

group var1 var2 myvar 
group1 1 a 100 
group2 2 b 200 
group2 34 c 300 
group3 5 d 400 
group3 6 e 500 
group4 7 f
600 

and I woud like to apply this function to column myvar: 

mifunc = function(vec) {
vec=as.vector(vec)
for (i in 1:(length(vec)-1)){
vec[i]=vec[i+1]-1
}
return(vec)
}
by the groups in column group. I would like to obtain the same dataframe but 
with f(myvar) instead of myvar.

How can I do this?

Thanks, 
Estefania
    [[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible
code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function within different groups

2013-05-23 Thread arun
Hi,
No problem.
Try:

dat2<-within(dat1,f_myvar<-ave(myvar,group,FUN=mifunc))
 dat2
#   group var1 var2 myvar f_myvar
#1 group1    1    a   100  NA
#2 group2    2    b   200 299
#3 group2   34    c   300 300
#4 group3    5    d   400 499
#5 group3    6    e   500 500
#6 group4    7    f   600  NA
A.K.



From: Estefanía Gómez Galimberti 
To: arun  
Cc: R help  
Sent: Thursday, May 23, 2013 12:08 PM
Subject: Re: [R] apply function within different groups



Thanks a lot!!! It works perkectly!
Just one thing, is there a way to preserve my original data frame so i don´t 
need to join both tables? I could do it with rbind but my original data frame 
is not in order, so
Thanks again!



From: arun 
To: Estefanía Gómez Galimberti  
Cc: R help  
Sent: Thursday, May 23, 2013 12:48 PM
Subject: Re: [R] apply function within different groups


Hi,

May be this helps:
dat1<- read.table(text="
group var1 var2 myvar
group1 1 a 100
group2 2 b 200
group2 34 c 300
group3 5 d 400
group3 6 e 500
group4 7 f 600
",sep="",header=TRUE,stringsAsFactors=FALSE)

library(plyr)
ddply(dat1,.(group),summarize, f_myvar=mifunc(myvar)) 
#   group f_myvar
#1 group1  NA
#2
group2 299
#3 group2 300
#4 group3 499
#5 group3 500
#6 group4  NA
A.K.



- Original Message -
From: Estefanía Gómez Galimberti 
To: r help help 
Cc: 
Sent: Thursday, May 23, 2013 11:30 AM
Subject: [R] apply function within different groups



Hi,

I have a very big data frame and I would like to apply a function to one of the 
columns within different groups  and obtain another dataframe
My data frame is like this:

group var1 var2 myvar 
group1 1 a 100 
group2 2 b 200 
group2 34 c 300 
group3 5 d 400 
group3 6 e 500 
group4 7 f
600 

and I woud like to apply this function to column myvar: 

mifunc = function(vec) {
vec=as.vector(vec)
for (i in 1:(length(vec)-1)){
vec[i]=vec[i+1]-1
}
return(vec)
}
by the groups in column group. I would like to obtain the same dataframe but 
with f(myvar) instead of myvar.

How can I do this?

Thanks, 
Estefania
    [[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible
code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function within different groups

2013-05-23 Thread Estefanía Gómez Galimberti
Thanks a lot!!! It works perkectly!
Just one thing, is there a way to preserve my original data frame so i don´t 
need to join both tables? I could do it with rbind but my original data frame 
is not in order, so
Thanks again!



 From: arun 
To: Estefanía Gómez Galimberti  
Cc: R help  
Sent: Thursday, May 23, 2013 12:48 PM
Subject: Re: [R] apply function within different groups


Hi,

May be this helps:
dat1<- read.table(text="
group var1 var2 myvar
group1 1 a 100
group2 2 b 200
group2 34 c 300
group3 5 d 400
group3 6 e 500
group4 7 f 600
",sep="",header=TRUE,stringsAsFactors=FALSE)

library(plyr)
ddply(dat1,.(group),summarize, f_myvar=mifunc(myvar)) 
#   group f_myvar
#1 group1  NA
#2 group2 299
#3 group2 300
#4 group3 499
#5 group3 500
#6 group4  NA
A.K.



- Original Message -
From: Estefanía Gómez Galimberti 
To: r help help 
Cc: 
Sent: Thursday, May 23, 2013 11:30 AM
Subject: [R] apply function within different groups



Hi,

I have a very big data frame and I would like to apply a function to one of the 
columns within different groups  and obtain another dataframe
My data frame is like this:

group var1 var2 myvar 
group1 1 a 100 
group2 2 b 200 
group2 34 c 300 
group3 5 d 400 
group3 6 e 500 
group4 7 f 600 

and I woud like to apply this function to column myvar: 

mifunc = function(vec) {
vec=as.vector(vec)
for (i in 1:(length(vec)-1)){
vec[i]=vec[i+1]-1
}
return(vec)
}
by the groups in column group. I would like to obtain the same dataframe but 
with f(myvar) instead of myvar.

How can I do this?

Thanks, 
Estefania
    [[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function within different groups

2013-05-23 Thread arun
Hi,

May be this helps:
dat1<- read.table(text="
group var1 var2 myvar
group1 1 a 100
group2 2 b 200
group2 34 c 300
group3 5 d 400
group3 6 e 500
group4 7 f 600
",sep="",header=TRUE,stringsAsFactors=FALSE)

library(plyr)
ddply(dat1,.(group),summarize, f_myvar=mifunc(myvar)) 
#   group f_myvar
#1 group1  NA
#2 group2 299
#3 group2 300
#4 group3 499
#5 group3 500
#6 group4  NA
A.K.



- Original Message -
From: Estefanía Gómez Galimberti 
To: r help help 
Cc: 
Sent: Thursday, May 23, 2013 11:30 AM
Subject: [R] apply function within different groups



Hi,

I have a very big data frame and I would like to apply a function to one of the 
columns within different groups  and obtain another dataframe
My data frame is like this:

group var1 var2 myvar 
group1 1 a 100 
group2 2 b 200 
group2 34 c 300 
group3 5 d 400 
group3 6 e 500 
group4 7 f 600 

and I woud like to apply this function to column myvar: 

mifunc = function(vec) {
vec=as.vector(vec)
for (i in 1:(length(vec)-1)){
vec[i]=vec[i+1]-1
}
return(vec)
}
by the groups in column group. I would like to obtain the same dataframe but 
with f(myvar) instead of myvar.

How can I do this?

Thanks, 
Estefania
    [[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function within different groups

2013-05-23 Thread Estefanía Gómez Galimberti


Hi,

I have a very big data frame and I would like to apply a function to one of the 
columns within different groups  and obtain another dataframe
My data frame is like this:

group var1 var2 myvar 
group1 1 a 100 
group2 2 b 200 
group2 34 c 300 
group3 5 d 400 
group3 6 e 500 
group4 7 f 600 

and I woud like to apply this function to column myvar: 

mifunc = function(vec) {
vec=as.vector(vec)
for (i in 1:(length(vec)-1)){
vec[i]=vec[i+1]-1
}
return(vec)
}
by the groups in column group. I would like to obtain the same dataframe but 
with f(myvar) instead of myvar.

How can I do this?

Thanks, 
Estefania
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-03 Thread gail
Excellent, thank you to both of you!!!
Gail



--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4639009.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]


Thanks Elk,
That was the missing link.
#or
 lapply(list6,function(x)max(x$target))
[[1]]
[1] 6

[[2]]
[1] 18

[[3]]
[1] 9
max(unlist(lapply(list6,function(x) max(x$target
A.K.



___
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638942.html

To unsubscribe from apply function over same column of all objects in a list, 
visit 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=unsubscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread Eik Vettorazzi
Hi Arun,
if you name the data.frame in the list, e.g.
mango <- list( y=c(4,5,3,2,1,8), bw=c(4,18,12,3,4,9),
nn=paste0("a",1:6),target=data.frame(coconut=1:6))
banana <- list(target=data.frame(coconut=c(1,2,18,16,15)), y=c(4,5,9,2,1),
bw=c(4,18,22,3,4), nn=paste0("a",1:5))
pineapple <- list(target=data.frame(coconut=c(4,6,9)), y=c(8,24,12),
bw=c(14,31,36), nn=paste0("a",1:3))
list6<-list(mango,banana,pineapple)

then
sapply(lapply(list5,"[[","target"),max)

still works.

Regards

Am 02.08.2012 20:21, schrieb arun kirshna [via R]:
> Hi Elk,
> 
> I tried to test with another case where coconut is in different position in
> the sublist.
> mango <- list( y=c(4,5,3,2,1,8), bw=c(4,18,12,3,4,9),
> nn=paste0("a",1:6),data.frame(coconut=1:6))
> banana <- list(data.frame(coconut=c(1,2,18,16,15)), y=c(4,5,9,2,1),
> bw=c(4,18,22,3,4), nn=paste0("a",1:5))
> pineapple <- list(data.frame(coconut=c(4,6,9)), y=c(8,24,12),
> bw=c(14,31,36), nn=paste0("a",1:3)) 
> list5<-list(mango,banana,pineapple)
> #Your code
> fun<-max # or min, median etc
> sapply(lapply(list5,"[[",1),fun) 
> [1]  8 18  9
> # Here, first number should be 6, instead it did the max of y from mango.
> #Then, I tried second solution of yours
> sapply(lapply(lapply(list5,"[[",1),"[[","coconut"),fun) 
> #Error in FUN(X[[1L]], ...) : subscript out of bounds
> #Third solution
>  sapply(lapply(list5,function(x)x[[1]][["coconut"]]),fun)
> #Error in x[[1]][["coconut"]] : subscript out of bounds
> 
> #I tried with another way to come up with the result (not as elegant)
> b3<-do.call("c",list5)
> names(b3)[4]<-"mango"
>  names(b3)[5]<-"banana"
>  names(b3)[9]<-"pineapple"
>  b4<-data.frame(key=names(b3),value=unlist(lapply(b3,FUN=function(x)
> max(x
>  key1<-c("mango","banana","pineapple")
>  b5<-subset(b4, b4$key%in% key1)
>  b5
> #key value
> #4 mango 6
> #5banana18
> #9 pineapple 9
> b6<-within(b5,{value<-as.numeric(as.character(value))})
> max(b6$value)
> #[1] 18
> A.K.
> 
> 
> 
> 
> 
> 
> __
> If you reply to this email, your message will be added to the discussion 
> below:
> http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638926.html
> This email was sent by arun kirshna (via Nabble)
> 
>   [[alternative HTML version deleted]]
> 
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 


-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/7410-58243
F ++49/40/7410-57790

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]
Hi Elk,

I tried to test with another case where coconut is in different position in
the sublist.
mango <- list( y=c(4,5,3,2,1,8), bw=c(4,18,12,3,4,9),
nn=paste0("a",1:6),data.frame(coconut=1:6))
banana <- list(data.frame(coconut=c(1,2,18,16,15)), y=c(4,5,9,2,1),
bw=c(4,18,22,3,4), nn=paste0("a",1:5))
pineapple <- list(data.frame(coconut=c(4,6,9)), y=c(8,24,12),
bw=c(14,31,36), nn=paste0("a",1:3)) 
list5<-list(mango,banana,pineapple)
#Your code
fun<-max # or min, median etc
sapply(lapply(list5,"[[",1),fun) 
[1]  8 18  9
# Here, first number should be 6, instead it did the max of y from mango.
#Then, I tried second solution of yours
sapply(lapply(lapply(list5,"[[",1),"[[","coconut"),fun) 
#Error in FUN(X[[1L]], ...) : subscript out of bounds
#Third solution
 sapply(lapply(list5,function(x)x[[1]][["coconut"]]),fun)
#Error in x[[1]][["coconut"]] : subscript out of bounds

#I tried with another way to come up with the result (not as elegant)
b3<-do.call("c",list5)
names(b3)[4]<-"mango"
 names(b3)[5]<-"banana"
 names(b3)[9]<-"pineapple"
 b4<-data.frame(key=names(b3),value=unlist(lapply(b3,FUN=function(x)
max(x
 key1<-c("mango","banana","pineapple")
 b5<-subset(b4, b4$key%in% key1)
 b5
#key value
#4 mango 6
#5banana18
#9 pineapple 9
b6<-within(b5,{value<-as.numeric(as.character(value))})
max(b6$value)
#[1] 18
A.K.






__
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638926.html
This email was sent by arun kirshna (via Nabble)

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]
Hello,

I was in a hurry at the time, when I replied.
You could do one thing: extract sublist using:
list4 <- list(mango, banana, pineapple) 
b1<-list()
 for(i in 1:3){
 b1[[i]]<-list()
 b1[[i]]<-list4[[i]][1]
 }
 b1
b<-list()
 for(i in 1:3){
 b[[i]]<-list()
 b[[i]]<-lapply(b1[[i]][[1]],FUN=function(x)x[which.max(x)])
 }

b2<-data.frame(do.call(rbind,b))
row.names(b2)<-c("mango","banana","pineapple")
 b2 
 apply(b2,2, function(x) x[which.max(x)]) 
$coconut
$coconut$banana
[1] 18

I guess, this is much better than calling individual sublists.
A.K.




__
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638907.html
This email was sent by arun kirshna (via Nabble)
To receive all replies by email, subscribe to this discussion: 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=subscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]



Hi Elk,
Thanks for the input.  Somehow, I got entangled with which.max.  I should
have used max. 
lapply(list4,function(x) max(x[[1]]$coconut))
[[1]]
[1] 6

[[2]]
[1] 18

[[3]]
[1] 9
 max(unlist(lapply(list4,function(x) max(x[[1]]$coconut
#[1] 18
A.K.








___
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638923.html

To unsubscribe from apply function over same column of all objects in a list, 
visit 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=unsubscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread Eik Vettorazzi
I still try to figure out, what you are finally asking for, but maybe

res<-sapply(list4,function(x)max(x[[1]]$coconut))
names(res)<-c("mango", "banana", "pineapple")
res
max(res)

is worth a try?

Especially i did not get the point of doing something like
x[which.max(x)] because this is in any case just max(x)

if you would like to plug in different functions or want to select
different columns,

fun<-max # or min, median etc
sapply(lapply(list4,"[[",1),fun)

could be a start, where lapply(list4,"[[",1) extracts the first object
in each sublist - which is in your case a data.frame with just one
column ('coconut'), where 'fun' can be applied to. So to address
'coconut' explicitly, just nest this lapply approach:

sapply(lapply(lapply(list4,"[[",1),"[[","coconut"),fun)
#or use an anonymous extractor function
sapply(lapply(list4,function(x)x[[1]][["coconut"]]),fun)

cheers

Am 02.08.2012 16:09, schrieb gail:
> Hi,
> 
> my dataset is the result of the function "density" on another set of data.
> It refers to that data in its variable "call", though since all the results
> are actually reproduced (except that I've removed all rows bar 10), I am not
> sure why R still needs it. But I've understood now why your code doesn't
> work on my data: your sublists are still just dataframes, whereas my
> sublists contain all sorts of vectors (2 numerical vectors and 5 other
> things). I've changed your data to make it look a bit more like mine, and
> you'll see that the code doesn't work. 
> 
> mango <- list(data.frame(coconut=1:6), y=c(4,5,3,2,1,8),
> bw=c(4,18,12,3,4,9), nn=paste0("a",1:6))
> banana <- list(data.frame(coconut=c(1,2,18,16,15)), y=c(4,5,9,2,1),
> bw=c(4,18,22,3,4), nn=paste0("a",1:5))
> pineapple <- list(data.frame(coconut=c(4,6,9)), y=c(8,24,12),
> bw=c(14,31,36), nn=paste0("a",1:3))
> list4 <- list(mango, banana, pineapple)
> 
> b <- list()
> 
>  for(i in 1:3){
>  b[[i]] <- list()
>  b[[i]] <- lapply (list4[[i]]$coconut, FUN=function(x) x[which.max(x)])
>  }
> 
> b
> summary( b)
> 
> What I want to end up with is the following:
> 
>coconut
> mango   6
> banana 18
> pineapple   9
> (that's for the individual sublists)
> 
> and 
>coconut
> 18
> (that's for the list as a whole).
> 
> Hope this is becoming a bit clearer ...
> 
> 
> 
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638876.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 


-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/7410-58243
F ++49/40/7410-57790

--
Pflichtangaben gemäß Gesetz über elektronische Handelsregister und 
Genossenschaftsregister sowie das Unternehmensregister (EHUG):

Universitätsklinikum Hamburg-Eppendorf; Körperschaft des öffentlichen Rechts; 
Gerichtsstand: Hamburg

Vorstandsmitglieder: Prof. Dr. Guido Sauter (Vertreter des Vorsitzenden), Dr. 
Alexander Kirstein, Joachim Prölß, Prof. Dr. Dr. Uwe Koch-Gromus 

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]
Hello,

If I understand it now, can't you do this:
Individual cases:
 list4<-list(mango[[1]],banana[[1]],pineapple[[1]])
b<-list()
 for(i in 1:3){
 b[[i]]<-list()
 b[[i]]<-lapply(list4[[i]],FUN=function(x)x[which.max(x)])
 }
b1<-data.frame(do.call(rbind,b))
row.names(b1)<-c("mango","banana","pineapple")
 b1
  coconut
mango   6
banana 18
pineapple   9
apply(b1,2, function(x) x[which.max(x)])
#$coconut
#$coconut$banana
#[1] 18

#This is what you asked for the result.
A.K.





__
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638886.html
This email was sent by arun kirshna (via Nabble)
To receive all replies by email, subscribe to this discussion: 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=subscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread gail
Hi,

my dataset is the result of the function "density" on another set of data.
It refers to that data in its variable "call", though since all the results
are actually reproduced (except that I've removed all rows bar 10), I am not
sure why R still needs it. But I've understood now why your code doesn't
work on my data: your sublists are still just dataframes, whereas my
sublists contain all sorts of vectors (2 numerical vectors and 5 other
things). I've changed your data to make it look a bit more like mine, and
you'll see that the code doesn't work. 

mango <- list(data.frame(coconut=1:6), y=c(4,5,3,2,1,8),
bw=c(4,18,12,3,4,9), nn=paste0("a",1:6))
banana <- list(data.frame(coconut=c(1,2,18,16,15)), y=c(4,5,9,2,1),
bw=c(4,18,22,3,4), nn=paste0("a",1:5))
pineapple <- list(data.frame(coconut=c(4,6,9)), y=c(8,24,12),
bw=c(14,31,36), nn=paste0("a",1:3))
list4 <- list(mango, banana, pineapple)

b <- list()

 for(i in 1:3){
 b[[i]] <- list()
 b[[i]] <- lapply (list4[[i]]$coconut, FUN=function(x) x[which.max(x)])
 }

b
summary( b)

What I want to end up with is the following:

   coconut
mango   6
banana 18
pineapple   9
(that's for the individual sublists)

and 
   coconut
18
(that's for the list as a whole).

Hope this is becoming a bit clearer ...



--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638876.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread gail
Michael, here is the data I am working with. I've shortened it without, I
trust, changing its nature. I am not using any package other than what is
pre-installed. Many thanks, Gail

> dput(list.example)

list

(structure(list(

x = c(379.455895016957, 380.116796110287, 
380.777697203618, 381.438598296949, 382.099499390279, 382.76040048361, 
383.421301576941, 384.082202670271, 384.743103763602, 385.404004856933, 
386.064905950264, 386.725807043594), 

y = c(7.66474496376218e-06, 
6.43440919959401e-06, 5.36894293042274e-06, 4.45194069157015e-06, 
3.66781132570054e-06, 3.00181397191447e-06, 2.45773671502347e-06, 
2.0034233225e-06, 1.62212866305772e-06, 1.3043460449395e-06, 
1.04141214324248e-06, 8.26430099678339e-07), 

bw = 9.02854660253144, 

n = 1102L,

call = density.default(x = read.table(paste(locuteur, 
i, sep = ""))$V1[read.table(paste(locuteur, i, sep = ""))$V1 != 
0]),

data.name = c("read.table(paste(locuteur, i, sep =
\"\"))$V1[read.table(paste(locuteur, ", 
"i, sep = \"\"))$V1 != 0]"), has.na = FALSE),

.Names = c("x", 
"y", "bw", "n", "call", "data.name", "has.na"),

class = "density"),

structure(list(x = c(372.576546447762, 373.241257067042, 
373.905967686322, 374.570678305602, 375.235388924882, 375.900099544162, 
376.564810163442, 377.229520782722, 377.894231402002, 378.558942021282, 
379.223652640562, 379.888363259842), y = c(1.60229850505427e-05, 
1.30822330219271e-05, 1.05973406669671e-05, 8.51514876035057e-06, 
6.78543779138952e-06, 5.41596769065147e-06, 4.28876937728122e-06, 
3.36815237991786e-06, 2.62273082547721e-06, 2.02454969122432e-06, 
1.54894049348427e-06, 1.18505840947482e-06), bw = 7.90353278894747, 
n = 1409L, call = density.default(x = read.table(paste(locuteur, 
i, sep = ""))$V1[read.table(paste(locuteur, i, sep = ""))$V1 != 
0]), data.name = c("read.table(paste(locuteur, i, sep =
\"\"))$V1[read.table(paste(locuteur, ", 
"i, sep = \"\"))$V1 != 0]"), has.na = FALSE), .Names = c("x", 
"y", "bw", "n", "call", "data.name", "has.na"), class = "density"),

structure(list(x = c(383.473231160603, 384.169713215726, 
384.866195270849, 385.562677325973, 386.259159381096, 386.955641436219, 
387.652123491343, 388.348605546466, 389.045087601589, 389.741569656713, 
390.438051711836, 391.134533766959), y = c(2.40798446492758e-06, 
2.04205952412882e-06, 1.72782287870817e-06, 1.45399002130161e-06, 
1.21665858527511e-06, 1.01213493683702e-06, 8.37503296444613e-07, 
6.94344355906326e-07, 5.72200769661348e-07, 4.6862434236517e-07, 
3.81353514437358e-07, 3.08309463721622e-07), bw = 10.0108886969865, 
n = 1522L, call = density.default(x = read.table(paste(locuteur, 
i, sep = ""))$V1[read.table(paste(locuteur, i, sep = ""))$V1 != 
0]), data.name = c("read.table(paste(locuteur, i, sep =
\"\"))$V1[read.table(paste(locuteur, ", 
"i, sep = \"\"))$V1 != 0]"), has.na = FALSE), .Names = c("x", 
"y", "bw", "n", "call", "data.name", "has.na"), class = "density"),

NULL, NULL, NULL, NULL, NULL, NULL)




--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638865.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread gail
Well but the whole point was to be able to plug in a single command and get
the result for all sublists. If I have to create a new list and type in each
sublist and the column I'm interested in, that completely defeats the
purpose, I might as well just ask for max(sublist$coconut) for each sublist,
that would be just as fast ...



--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p463.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread gail
Arun, I see you've defined dat5 in your later message; however the same
applies as to the above: the code doesn't work if the list contains
non-numerical elements.
Gail



--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638859.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]
Hi,
I am not able to read your dataset.
Getting errors.
source("list1.txt")
Error in paste(locuteur, i, sep = "") : object 'locuteur' not found
Please check.
A.K.




__
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638873.html
This email was sent by arun kirshna (via Nabble)
To receive all replies by email, subscribe to this discussion: 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=subscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-02 Thread arun kirshna [via R]
Hello Gail,

The dat5 was in earlier post.  I forgot to paste it.
Now, your question regarding individual cases,
This is a case that includes nonnumeric columns
list1<-list(data.frame(x=1:6,y=c(4,5,3,2,1,8),bw=c(4,18,12,3,4,9),nn=paste0("a",1:6)))
list2<-list(data.frame(x=c(1,2,18,16,15),y=c(4,5,9,2,1),bw=c(4,18,22,3,4),nn=paste0("a",1:5)))

list3<-list(data.frame(x=c(4,6,9),y=c(8,24,12),bw=c(14,31,36),nn=paste0("a",1:3)))
 
 list4<-list(list1,list2,list3)
b<-list()
 for(i in 1:3){
 b[[i]]<-list()
 b[[i]]<-lapply(list4[[i]][[1]],FUN=function(x) x[which.max(x)])
 }
 b
[[1]]
[[1]]$x
[1] 6

[[1]]$y
[1] 8

[[1]]$bw
[1] 18

[[1]]$nn
[1] a6
Levels: a1 a2 a3 a4 a5 a6


[[2]]
[[2]]$x
[1] 18

[[2]]$y
[1] 9

[[2]]$bw
[1] 22

[[2]]$nn
[1] a5
Levels: a1 a2 a3 a4 a5


[[3]]
[[3]]$x
[1] 9

[[3]]$y
[1] 24

[[3]]$bw
[1] 36

[[3]]$nn
[1] a3
Levels: a1 a2 a3

I haven't looked into your dataset that was posted now.  The main problem
was that I was constructing my own data, guessing how your dataset looks
like.

A.K>





__
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638870.html
This email was sent by arun kirshna (via Nabble)
To receive all replies by email, subscribe to this discussion: 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=subscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-01 Thread arun kirshna [via R]
HI,
I tested the code for another set of data with added complexity.  Seems to
be working fine.
list1<-list(data.frame(x=1:6,y=c(4,5,3,2,1,8),bw=c(4,18,12,3,4,9)))
list2<-list(data.frame(x=c(1,2,18,16,15),y=c(4,5,9,2,1),bw=c(4,18,22,3,4)))
list3<-list(data.frame(x=c(4,6,9),y=c(8,24,12),bw=c(14,31,36)))
list4<-list(list1,list2,list3)
#individual cases
lapply(list4[[1]][[1]],FUN=function(x) x[which.max(x)])
lapply(list4[[2]][[1]],FUN=function(x) x[which.max(x)])
 lapply(list4[[3]][[1]],FUN=function(x) x[which.max(x)])

#Whole set
flatlist <- function(mylist){
   lapply(rapply(mylist, enquote, how="unlist"), eval)
 }
 list5<-flatlist(list4)
dat6<-data.frame(key=names(list5),dat5)
 dat6
aggregate(value~key,data=dat6,max)
  #key value
#1  bw36
#2   x18
#3   y24
A.K. 




__
If you reply to this email, your message will be added to the discussion below:
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638829.html
This email was sent by arun kirshna (via Nabble)
To receive all replies by email, subscribe to this discussion: 
http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=subscribe_by_code&node=4638681&code=ci1oZWxwQHItcHJvamVjdC5vcmd8NDYzODY4MXwtNzg0MjM1NTA4
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-01 Thread R. Michael Weylandt
I'm a little confused on your data structure -- can you use dput() as
described here [1] to give a small reproducible example?

http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example

Michael

On Wed, Aug 1, 2012 at 10:38 AM, gail  wrote:
> Thank you!!! But I realise I've simplified my data to the point that your
> solution doesn't actually work -- not your fault, mine! My list is actually
> more complicated than what I presented it to be; it's not composed of
> numerical matrices but of lists, each being composed of 7 columns, the first
> two of each (the ones that I am interested in, x and y) being numerical.
> This is what my list really looks like (truncated):
>
>> summary(mylist)
>   Length Class   Mode
> moh6  7  density list
> moh7  7  density list
> moh8  7  density list
> ...
> etc.
>
>> summary(mylist[[3]]) # I've taken number 3 as an example, but they're all
>> the same
>   Length Class  Mode
> x 512-none- numeric
> y 512-none- numeric
> bw  1-none- numeric
> n   1-none- numeric
> call2-none- call
> data.name   1-none- character
> has.na  1-none- logical
>
> Any suggestion how to get the max of column y for each sub-list (moh6, moh7,
> moh8 etc.), and to the max of all these individual maxes? By the way,
>
> lapply(list1,FUN=function(x)x[,2][which.max(x[,2])])
>
> gives me the individual maxes (for a list composed of numerical matrices),
> but how do I get to the overall max?

Possibly

max(unlist(list1))

if I understand you correctly.

>
> Many thanks ...
>
>
>
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638705.html
> Sent from the R help mailing list archive at Nabble.com.
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-01 Thread R. Michael Weylandt
On Wed, Aug 1, 2012 at 8:43 AM, gail  wrote:
> Hello. Please forgive me if this problem has already been posted (and solved)
> by someone else ... I can't find it anywhere though it seems so very basic.
> Here it is:
>
> I have a list comprised of several matrices, each of which has two columns.
>
>> list
> [[1]]
> [,1] [,2]
> [1,]1 3
> [2,]2 4
>
> [[2]]
> [,1] [,2]
> [1,]5 7
> [2,]6 8
>
> [[3]]
> [,1]   [,2]
> [1,]9  11
> [2,]1012
>
> I would like R to give me the highest value (max) of each matrice's 2nd
> column, and also the max of all those individual highest values. I have
> tried
>
> matrix.max <- for (i in 1:3) {
> mapply ( max, list [[i]] [2] )
> }
>
> for each column's max and
>
> total.max <- for (i in 1:3) {
> max(mapply ( max, list [[i]] [2] ))
> }
>

I think what you just want is to put the "get second column" part
within the function that you apply() [Actually lapply() since you have
a list] -- to put it another way, note that "get the second column"
can be considered part of the operation you perform on each list
element, rather than defining the thing to which you apply the max()
function.

Something like this results:

lapply(list, function(x) max(x[,2]))

This will go over the list and apply the function "get the max of the
second column"

Best,
Michael

> for the total max, but neither works (result: NULL). What am I doing wrong?
>
>  Thanks a lot,
> Gail
>
>
>
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681.html
> Sent from the R help mailing list archive at Nabble.com.
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function over same column of all objects in a list

2012-08-01 Thread gail
Thank you!!! But I realise I've simplified my data to the point that your
solution doesn't actually work -- not your fault, mine! My list is actually
more complicated than what I presented it to be; it's not composed of
numerical matrices but of lists, each being composed of 7 columns, the first
two of each (the ones that I am interested in, x and y) being numerical.
This is what my list really looks like (truncated):

> summary(mylist)
  Length Class   Mode
moh6  7  density list
moh7  7  density list
moh8  7  density list
...
etc.

> summary(mylist[[3]]) # I've taken number 3 as an example, but they're all
> the same
  Length Class  Mode 
x 512-none- numeric  
y 512-none- numeric  
bw  1-none- numeric  
n   1-none- numeric  
call2-none- call 
data.name   1-none- character
has.na  1-none- logical  

Any suggestion how to get the max of column y for each sub-list (moh6, moh7,
moh8 etc.), and to the max of all these individual maxes? By the way,

lapply(list1,FUN=function(x)x[,2][which.max(x[,2])])

gives me the individual maxes (for a list composed of numerical matrices),
but how do I get to the overall max?

Many thanks ...



--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681p4638705.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function over same column of all objects in a list

2012-08-01 Thread gail
Hello. Please forgive me if this problem has already been posted (and solved)
by someone else ... I can't find it anywhere though it seems so very basic.
Here it is:

I have a list comprised of several matrices, each of which has two columns.

> list
[[1]]
[,1] [,2]
[1,]1 3
[2,]2 4

[[2]]
[,1] [,2]
[1,]5 7
[2,]6 8

[[3]]
[,1]   [,2]
[1,]9  11
[2,]1012

I would like R to give me the highest value (max) of each matrice's 2nd
column, and also the max of all those individual highest values. I have
tried 

matrix.max <- for (i in 1:3) {
mapply ( max, list [[i]] [2] )
}

for each column's max and 

total.max <- for (i in 1:3) {
max(mapply ( max, list [[i]] [2] ))
}

for the total max, but neither works (result: NULL). What am I doing wrong?

 Thanks a lot,
Gail



--
View this message in context: 
http://r.789695.n4.nabble.com/apply-function-over-same-column-of-all-objects-in-a-list-tp4638681.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply() function: margin argument: "2L" versus "2"

2012-06-22 Thread Bert Gunter
FYI below.

On Fri, Jun 22, 2012 at 4:00 PM, Luba G  wrote:

> Thanks Rui!
> I was not aware that *number*L is an alternate to as.integer(*number*).
> Luba
>
> > identical(2,as.integer(2))
[1] FALSE
> identical(2L,as.integer(2))
[1] TRUE

Cheers,
Bert



> On Fri, Jun 22, 2012 at 3:53 PM, Rui Barradas 
> wrote:
>
> > Hello,
> >
> > 2L is an integer, 2 might be or not. In the case of apply(), there is no
> > difference.
> >
> > All possible values for margin? Any possible(*) combination of the
> > dimensions of 'x' in
> >
> > apply(x, margin, function)
> >
> > (*) non-null. If, say, x <- array(0, dim=c(2,3,4)) (3dim) then you can
> > call any of
> >
> > apply(x, 1, fun) or apply(x, 2, fun) or apply(x, 3, fun) but not
> margin=4;
> > apply(x, 1:2, fun) or apply(x, c(1, 3), fun) or ...
> > apply(x, 1:3, fun)
> >
> > Hope this helps,
> >
> > Rui Barradas
> >
> > Em 22-06-2012 23:23, Luba G escreveu:
> >
> >> What is the difference of using 2L versus 2 as the margin argument in
> the
> >> apply() function? Where can I find detailed information on all of the
> >> possible margin arguments?
> >>
> >>  x
> >>>
> >>  [,1] [,2]
> >> [1,]12
> >> [2,]34
> >> [3,]56
> >> [4,]78
> >> [5,]9   10
> >>
> >>> sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))
> >>>
> >> [1] 3.162278 3.162278
> >>
> >>> sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))
> >>>
> >> [1] 3.162278 3.162278
> >>
> >>[[alternative HTML version deleted]]
> >>
> >> __**
> >> R-help@r-project.org mailing list
> >> https://stat.ethz.ch/mailman/**listinfo/r-help<
> https://stat.ethz.ch/mailman/listinfo/r-help>
> >> PLEASE do read the posting guide http://www.R-project.org/**
> >> posting-guide.html 
> >> and provide commented, minimal, self-contained, reproducible code.
> >>
> >
>
>[[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply() function: margin argument: "2L" versus "2"

2012-06-22 Thread Luba G
Thanks Rui!
I was not aware that *number*L is an alternate to as.integer(*number*).
Luba

On Fri, Jun 22, 2012 at 3:53 PM, Rui Barradas  wrote:

> Hello,
>
> 2L is an integer, 2 might be or not. In the case of apply(), there is no
> difference.
>
> All possible values for margin? Any possible(*) combination of the
> dimensions of 'x' in
>
> apply(x, margin, function)
>
> (*) non-null. If, say, x <- array(0, dim=c(2,3,4)) (3dim) then you can
> call any of
>
> apply(x, 1, fun) or apply(x, 2, fun) or apply(x, 3, fun) but not margin=4;
> apply(x, 1:2, fun) or apply(x, c(1, 3), fun) or ...
> apply(x, 1:3, fun)
>
> Hope this helps,
>
> Rui Barradas
>
> Em 22-06-2012 23:23, Luba G escreveu:
>
>> What is the difference of using 2L versus 2 as the margin argument in the
>> apply() function? Where can I find detailed information on all of the
>> possible margin arguments?
>>
>>  x
>>>
>>  [,1] [,2]
>> [1,]12
>> [2,]34
>> [3,]56
>> [4,]78
>> [5,]9   10
>>
>>> sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))
>>>
>> [1] 3.162278 3.162278
>>
>>> sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))
>>>
>> [1] 3.162278 3.162278
>>
>>[[alternative HTML version deleted]]
>>
>> __**
>> R-help@r-project.org mailing list
>> https://stat.ethz.ch/mailman/**listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/**
>> posting-guide.html 
>> and provide commented, minimal, self-contained, reproducible code.
>>
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply() function: margin argument: "2L" versus "2"

2012-06-22 Thread Rui Barradas

Right, I had missed that one.

To the op: what Michael is saying can be shown with the following example.

x <- array(1:24, c(2,3,4))

r1 <- apply(x, -1, sum)  # remove dim 1
r2 <- apply(x, 2:3, sum) # include dims 2 and 3

all.equal(r1, r2)  # FALSE, different attributes
all(r1 == r2)  # TRUE, equal values

A negative index removes that removes that value from a vector, or 
row/column from a matrix or data.frame, or list element, etc. The index 
must be a number, for instance, data.frame column NAMES can't be used.

c(1, 2, 3)[-2] is c(1, 3).

So, the two forms above should be equivalent, but they're not. The first 
doesn't keep the dim attribute.


Rui Barradas

Em 23-06-2012 00:00, R. Michael Weylandt escreveu:

On Fri, Jun 22, 2012 at 5:53 PM, Rui Barradas  wrote:

Hello,

2L is an integer, 2 might be or not. In the case of apply(), there is no
difference.

All possible values for margin? Any possible(*) combination of the
dimensions of 'x' in

apply(x, margin, function)

(*) non-null. If, say, x<- array(0, dim=c(2,3,4)) (3dim) then you can call
any of

apply(x, 1, fun) or apply(x, 2, fun) or apply(x, 3, fun) but not margin=4;
apply(x, 1:2, fun) or apply(x, c(1, 3), fun) or ...
apply(x, 1:3, fun)

You can also get away with negative indexing in apply():

x<- array(1:24, dim = c(2,3,4))

apply(x, -1, sum)
apply(x, -c(1,3), sum)

but you seem to loose the array structure.

As usual, you can't mix

apply(x, c(-1, 2), sum) # ERROR

It also seems zero doesn't work here:

apply(x, 0, sum) # ERROR

Best,
Michael


Hope this helps,

Rui Barradas

Em 22-06-2012 23:23, Luba G escreveu:


What is the difference of using 2L versus 2 as the margin argument in the
apply() function? Where can I find detailed information on all of the
possible margin arguments?


x

  [,1] [,2]
[1,]12
[2,]34
[3,]56
[4,]78
[5,]9   10

sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))

[1] 3.162278 3.162278

sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))

[1] 3.162278 3.162278

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply() function: margin argument: "2L" versus "2"

2012-06-22 Thread R. Michael Weylandt
On Fri, Jun 22, 2012 at 5:53 PM, Rui Barradas  wrote:
> Hello,
>
> 2L is an integer, 2 might be or not. In the case of apply(), there is no
> difference.
>
> All possible values for margin? Any possible(*) combination of the
> dimensions of 'x' in
>
> apply(x, margin, function)
>
> (*) non-null. If, say, x <- array(0, dim=c(2,3,4)) (3dim) then you can call
> any of
>
> apply(x, 1, fun) or apply(x, 2, fun) or apply(x, 3, fun) but not margin=4;
> apply(x, 1:2, fun) or apply(x, c(1, 3), fun) or ...
> apply(x, 1:3, fun)

You can also get away with negative indexing in apply():

x <- array(1:24, dim = c(2,3,4))

apply(x, -1, sum)
apply(x, -c(1,3), sum)

but you seem to loose the array structure.

As usual, you can't mix

apply(x, c(-1, 2), sum) # ERROR

It also seems zero doesn't work here:

apply(x, 0, sum) # ERROR

Best,
Michael

>
> Hope this helps,
>
> Rui Barradas
>
> Em 22-06-2012 23:23, Luba G escreveu:
>
>> What is the difference of using 2L versus 2 as the margin argument in the
>> apply() function? Where can I find detailed information on all of the
>> possible margin arguments?
>>
>>> x
>>
>>      [,1] [,2]
>> [1,]    1    2
>> [2,]    3    4
>> [3,]    5    6
>> [4,]    7    8
>> [5,]    9   10
>>>
>>> sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))
>>
>> [1] 3.162278 3.162278
>>>
>>> sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))
>>
>> [1] 3.162278 3.162278
>>
>>        [[alternative HTML version deleted]]
>>
>> __
>> R-help@r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply() function: margin argument: "2L" versus "2"

2012-06-22 Thread Rui Barradas

Hello,

2L is an integer, 2 might be or not. In the case of apply(), there is no 
difference.


All possible values for margin? Any possible(*) combination of the 
dimensions of 'x' in


apply(x, margin, function)

(*) non-null. If, say, x <- array(0, dim=c(2,3,4)) (3dim) then you can 
call any of


apply(x, 1, fun) or apply(x, 2, fun) or apply(x, 3, fun) but not margin=4;
apply(x, 1:2, fun) or apply(x, c(1, 3), fun) or ...
apply(x, 1:3, fun)

Hope this helps,

Rui Barradas

Em 22-06-2012 23:23, Luba G escreveu:

What is the difference of using 2L versus 2 as the margin argument in the
apply() function? Where can I find detailed information on all of the
possible margin arguments?


x

  [,1] [,2]
[1,]12
[2,]34
[3,]56
[4,]78
[5,]9   10

sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))

[1] 3.162278 3.162278

sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))

[1] 3.162278 3.162278

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply() function: margin argument: "2L" versus "2"

2012-06-22 Thread Luba G
What is the difference of using 2L versus 2 as the margin argument in the
apply() function? Where can I find detailed information on all of the
possible margin arguments?

> x
 [,1] [,2]
[1,]12
[2,]34
[3,]56
[4,]78
[5,]9   10
> sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))
[1] 3.162278 3.162278
> sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))
[1] 3.162278 3.162278

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 'nth' element of a vector

2012-04-05 Thread Michael Bach
Thank you very much for your comments Ista and David! I will
experiment and see which one serves my needs best.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 'nth' element of a vector

2012-04-05 Thread David Winsemius


On Apr 5, 2012, at 7:01 AM, Michael Bach wrote:


Dear R users,

how do I e.g. square each second element of a vector with an even
number of elements? Or more generally to apply a function to every
'nth' element of a vector. I looked into the apply functions, but
found no hint.

For example:

v <- c(1, 2, 3, 4)
mysquare <- function (x) { return (x*x) }
w <- applyfun(v, mysquare, 2)

then w should be c(1, 4, 3, 16)


An alternate approach to the ifelse() solutions you have been offered  
is to use identical indexing on both sides of an assignment function.


> v <- c(1, 2, 3, 4)
> w <-v
> w[seq(2, length(w), by =2)] <-w[seq(2, length(w), by =2)]^2
> w
[1]  1  4  3 16

If you still wanted to create a function that would square each  
element "in place" you could do this with an indexing strategy:


 v <- c(1, 2, 3, 4)
 w <-v
 mysqr <- function (x) { eval.parent(substitute(x <- x^2))  }
 mysqr(w[seq(2, length(w), by =2)])
 w
#[1]  1  4  3 16

(Credit: http://www.statisticsblog.com/2011/10/waiting-in-line-waiting-on-r/ 
 and search on 'inc')




Thanks for your time,
Michael Bach

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


David Winsemius, MD
West Hartford, CT

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 'nth' element of a vector

2012-04-05 Thread ken knoblauch
ken knoblauch  inserm.fr> writes:

> 
> Michael Bach  gmail.com> writes:
> > how do I e.g. square each second element of a 
> vector with an even
> > number of elements? Or more generally to 
> apply a function to every
> > 'nth' element of a vector. I looked into the 
> apply functions, but
> > found no hint.
> > For example:
> > v <- c(1, 2, 3, 4)
> > mysquare <- function (x) { return (x*x) }
> > w <- applyfun(v, mysquare, 2)
> > then w should be c(1, 4, 3, 16)
> > Michael Bach
> 
> Hi Michael,
> 
> v^(2 - seq_along(v) %% 2)
> 
> [1]  1  4  3 16
> 
> Ken
> 
Actually, combining Ista and my responses, 
a general response could be
something like

ifelse(v %% n, v, function(v){} )

where you have set n and define some
function

HTH,

Ken

-- 
Ken Knoblauch
Inserm U846
Stem-cell and Brain Research Institute
Department of Integrative Neurosciences
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.sbri.fr/members/kenneth-knoblauch.html

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 'nth' element of a vector

2012-04-05 Thread ken knoblauch
Michael Bach  gmail.com> writes:
> how do I e.g. square each second element of a 
vector with an even
> number of elements? Or more generally to 
apply a function to every
> 'nth' element of a vector. I looked into the 
apply functions, but
> found no hint.
> For example:
> v <- c(1, 2, 3, 4)
> mysquare <- function (x) { return (x*x) }
> w <- applyfun(v, mysquare, 2)
> then w should be c(1, 4, 3, 16)
> Michael Bach

Hi Michael,

v^(2 - seq_along(v) %% 2)

[1]  1  4  3 16

Ken

-- 
Ken Knoblauch
Inserm U846
Stem-cell and Brain Research Institute
Department of Integrative Neurosciences
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.sbri.fr/members/kenneth-knoblauch.html

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to every 'nth' element of a vector

2012-04-05 Thread Ista Zahn
Good morning Michael,

On Thu, Apr 5, 2012 at 7:01 AM, Michael Bach  wrote:
> Dear R users,
>
> how do I e.g. square each second element of a vector with an even
> number of elements? Or more generally to apply a function to every
> 'nth' element of a vector. I looked into the apply functions, but
> found no hint.

Use indexing, or ifelse.

>
> For example:
>
> v <- c(1, 2, 3, 4)
> mysquare <- function (x) { return (x*x) }
> w <- applyfun(v, mysquare, 2)
>
> then w should be c(1, 4, 3, 16)

Here is one way:

 w <- ifelse(v %in% seq(1, length(v), 2), v, v^2)

Best,
Ista

>
> Thanks for your time,
> Michael Bach
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply function to every 'nth' element of a vector

2012-04-05 Thread Michael Bach
Dear R users,

how do I e.g. square each second element of a vector with an even
number of elements? Or more generally to apply a function to every
'nth' element of a vector. I looked into the apply functions, but
found no hint.

For example:

v <- c(1, 2, 3, 4)
mysquare <- function (x) { return (x*x) }
w <- applyfun(v, mysquare, 2)

then w should be c(1, 4, 3, 16)

Thanks for your time,
Michael Bach

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply Function to List by Group Returning Result with Dim of List

2012-01-19 Thread jamesrobinsonjnr
Excellent.

Thank you very much David. Your help is greatly appreciated. "ave" worked
like a charm. 

James

--
View this message in context: 
http://r.789695.n4.nabble.com/Apply-Function-to-List-by-Group-Returning-Result-with-Dim-of-List-tp4311880p4312262.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply Function to List by Group Returning Result with Dim of List

2012-01-19 Thread David Winsemius


On Jan 19, 2012, at 6:42 PM, jamesrobinsonjnr wrote:

I have a panel data set defined as a simple data.frame with a factor  
age and
income. I would like to generate the results of a set function such  
as (sum,

mean, or even diff) separate for each factor (category or age group).
However I want the result to have the same dimension as the overal
data.frame. Therefore, I expect to get repeaded the same result for  
each

item within a category, but different accross categories.

Eg:
ageincomeavg_inc
20 100   100
20   90   100
20 110   100
30  200  200
30  250  200
30  150  200


?ave  (which returnsf the same length as the first argument.)

?tapply
?aggregate (neither which will yield that same number of items

(There are also the doBy and plyr packages.)




What builtin function can assist in doing this without my having to  
write
loops. I know in Eviews there is the sumsby, meansby, minsby and so  
forth.



--
David Winsemius, MD
West Hartford, CT

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply Function to List by Group Returning Result with Dim of List

2012-01-19 Thread jamesrobinsonjnr
I have a panel data set defined as a simple data.frame with a factor age and
income. I would like to generate the results of a set function such as (sum,
mean, or even diff) separate for each factor (category or age group).
However I want the result to have the same dimension as the overal
data.frame. Therefore, I expect to get repeaded the same result for each
item within a category, but different accross categories. 

Eg:
ageincomeavg_inc
20 100   100
20   90   100  
20 110   100
30  200  200
30  250  200
30  150  200

What builtin function can assist in doing this without my having to write
loops. I know in Eviews there is the sumsby, meansby, minsby and so forth.

--
View this message in context: 
http://r.789695.n4.nabble.com/Apply-Function-to-List-by-Group-Returning-Result-with-Dim-of-List-tp4311880p4311880.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to spatial grid data frame to calculate CTI

2011-08-25 Thread Paul Hiemstra
 On 08/25/2011 10:54 AM, Tom Vanwalleghem wrote:
> Dear R helpers,
> I'm new to R and struggling with applying functions to a spatial grid data 
> frame, called data for example.data has a variable named "slope" and "uparea"
> Basically, I need to calculate the tan(data$slope)Next, I need to divide 
> data$uparea by data$slope and take the log() of that all
> In the basic examples I found how to make simple multiplications with a 
> scalar likedata[["slope"]] = data[["slope"]]/2 # assigns new attribute
> I come from a background in GIS and fortran, so used to dealing with ordinary 
> matrices, I'll admit I'm having trouble with understanding the format of this 
> spatial grid data frame structureI've been trying different methods to index 
> the data frame, or working with the function "lapply" but so far I can't seem 
> to get my head wrapped around it.
> I appreciate any help.TomResearcher@University of CordobaSpain
>   
>   [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
I would most surely take a look at the raster package, this might also
be more intuitive for you. In addition, there is a special mailing list
for spatial tasks, r-sig-geo. These kinds of questions are more suitable
for that mailing list.

cheers,
Paul

-- 
Paul Hiemstra, Ph.D.
Global Climate Division
Royal Netherlands Meteorological Institute (KNMI)
Wilhelminalaan 10 | 3732 GK | De Bilt | Kamer B 3.39
P.O. Box 201 | 3730 AE | De Bilt
tel: +31 30 2206 494

http://intamap.geo.uu.nl/~paul
http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to spatial grid data frame to calculate CTI

2011-08-25 Thread Jean V Adams
It's not clear to me what problem you're having.

   tan(data$slope)

should work.  As should

   log(data$uparea/data$slope)

I suggest that you provide a small subset of example data along with an 
example of any code you've tried, and the output that you'd like.

Jean

Tom Vanwalleghem wrote on 08/25/2011 05:54:01 AM:
> 
> Dear R helpers,
> I'm new to R and struggling with applying functions to a spatial 
> grid data frame, called data for example.data has a variable named 
> "slope" and "uparea"
> Basically, I need to calculate the tan(data$slope)Next, I need to 
> divide data$uparea by data$slope and take the log() of that all
> In the basic examples I found how to make simple multiplications 
> with a scalar likedata[["slope"]] = data[["slope"]]/2 # assigns new 
attribute
> I come from a background in GIS and fortran, so used to dealing with
> ordinary matrices, I'll admit I'm having trouble with understanding 
> the format of this spatial grid data frame structureI've been trying
> different methods to index the data frame, or working with the 
> function "lapply" but so far I can't seem to get my head wrapped around 
it.
> I appreciate any help.TomResearcher@University of CordobaSpain  
>[[alternative HTML version deleted]]
> 

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function to spatial grid data frame to calculate CTI

2011-08-25 Thread Tom Vanwalleghem

Dear R helpers,
I'm new to R and struggling with applying functions to a spatial grid data 
frame, called data for example.data has a variable named "slope" and "uparea"
Basically, I need to calculate the tan(data$slope)Next, I need to divide 
data$uparea by data$slope and take the log() of that all
In the basic examples I found how to make simple multiplications with a scalar 
likedata[["slope"]] = data[["slope"]]/2 # assigns new attribute
I come from a background in GIS and fortran, so used to dealing with ordinary 
matrices, I'll admit I'm having trouble with understanding the format of this 
spatial grid data frame structureI've been trying different methods to index 
the data frame, or working with the function "lapply" but so far I can't seem 
to get my head wrapped around it.
I appreciate any help.TomResearcher@University of CordobaSpain  
  
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function returning different results

2011-03-18 Thread Tanya Cashorali
For some reason when I apply a function to a single row in R it works, but
when that same row is in a data.frame it does not, see below:

apply(dx[954,], 1, query.db)
2571
1092  0.06044147
3890  0.05948577
3273  0.05911261
794   0.05855583
4241  0.05854064
3560  0.05602690

apply(dx[954:955,], 1, query.db)
$`2571`
numeric(0)

$`1194`
 908 3754 5119 2835 3139
2775
 0.028935504  0.026941886  0.024762815  0.023335049  0.021892711
0.021001654
1101 1762  401 3899 3727
4248
 0.020434257  0.020413724 -0.08333  0.020111260  0.019872379
0.019840807
3282 4585  798 5249  836
3570
 0.019729315  0.019524213  0.019440097  0.019410513  0.019288864
0.019052412
 726 3663 4775 3030 4938
3259
 0.018894556  0.018838258  0.018749506 -0.08333  0.018416353
0.018240173
1426 4563 3871  958 1242
1033


Here's the function code:

calc.enrichment <- function(cptdf){
if(cptdf[4] %in% cptcodes[,1]){
P.hit <- as.numeric(cptdf[6]) / sum.all.hits
return (P.hit)
} else{
return (-miss)
}

}

query.db <- function(dxdf){
snquery = dbSendQuery(connection, paste("select distinct cpt4code from
DxRxLookup where icd9code = '", dxdf[4], "'", sep = ""))
cptcodes <<- dbGetResult(snquery)

#restrict this to constrain by Rx1 and Rx2 inputs
h1 <<- which(cpt$Cpt %in% cptcodes[,1])
y <<- which((cpt$Rx2 %in% dxdf[2] | cpt$Rx1 %in% dxdf[2]) & (cpt$Rx1
%in% dxdf[3] | cpt$Rx2 %in% dxdf[3]))
hits <<- intersect(y, h1)
sum.all.hits <<- sum(cpt[hits,]$Log.Odds.Ratio)
miss <<- 1 / (length(y) - length(hits))
apply(cpt[y,], 1, calc.enrichment)
}

Thanks for any help!

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply Function To Each Row of Matrix

2011-02-14 Thread Stuart Jaffe
Hi,

I have a matrix with about 3000 rows, and 1 column. The contents of the matrix 
are stock symbols (IBM, AAPL, etc) for instance. I also have a function that 
takes a single stock symbol as an argument, parses the text of Google Finance 
and returns the related stock symbols that the page has listed into a CSV file. 
For example, IBM would return the following in a CSV file:
 rels
1  ORCL
2   HPQ
3  MSFT
4  CSCO
5   EMC
6  DELL
7   SAP
8  INTC
9SY
10   CA

I'm  trying to use sapply (or any of the apply functions) to loop through  the 
matrix of 3000 stock symbols and pass them through to my function. I  get the 
following errors when using sapply:

1: In file(con, "r") : only first  element of 'description' argument used
2: In if (file == "") file <- stdout() else if (is.character(file)) { ... :
  the condition has length > 1 and only the first element will be used
3: In file(file, ifelse(append, "a", "w")) :
  only first element of 'description' argument used

I  think it has something to do with the fact that I'm trying to pass a  vector 
as an argument into a function which only accepts a scalar  argument. I've also 
tried "do.call" but can't get any results. How do I  loop through the matrix in 
order to pass each individual stock symbol as  an argument into the function? 
Thanks so much for your help.



  
[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function over elemetns of a list

2010-10-02 Thread Uwe Ligges



On 02.10.2010 18:00, PQuery wrote:


Hello,

I have a list "ll - see below" on which I would like to apply a function
accessing every pair of elements in the list. For instance, I want to apply
the "sum" function on "6635 + 6636" and return the sum, the on "6635 +
6637", ...

Any hint to do that using apply / mapply / rapply ?

Thanks,


ll

[[1]]
[1] "6635" "6636"

[[2]]
[1] "6635" "6637"

[[3]]
[1] "6636" "6637"




sapply(ll, sum)

Uwe Ligges

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply function over elemetns of a list

2010-10-02 Thread PQuery

Hello,

I have a list "ll - see below" on which I would like to apply a function
accessing every pair of elements in the list. For instance, I want to apply
the "sum" function on "6635 + 6636" and return the sum, the on "6635 +
6637", ... 

Any hint to do that using apply / mapply / rapply ?

Thanks,

> ll
[[1]]
[1] "6635" "6636"

[[2]]
[1] "6635" "6637"

[[3]]
[1] "6636" "6637"
-- 
View this message in context: 
http://r.789695.n4.nabble.com/Apply-function-over-elemetns-of-a-list-tp2952538p2952538.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Apply function to two variables

2010-08-02 Thread Erik Iverson


I would like to apply a function to two vectors 


For example,

A<-c(NA,1,2,3,NA)
B<-6:10

I would like C to be equal to A but if any A element is NA that
corresponding c element is equal to B, i.e.

C = c(6,1,2,3,10)


#untested...
C <- ifelse(is.na(A), B, A)

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply function to two variables

2010-08-02 Thread Suphajak Ngamlak
Dear all,

I would like to apply a function to two vectors 

For example,

A<-c(NA,1,2,3,NA)
B<-6:10

I would like C to be equal to A but if any A element is NA that
corresponding c element is equal to B, i.e.

C = c(6,1,2,3,10)

Please note that this is a simplified example and the real vectors are
large so I would like to avoid loop as much as possible. Thank you 


Best Regards,

Suphajak Ngamlak
Equity and Derivatives Trading
Phatra Securities Public Company Limited
Tel: +662-305-9179   
Email: supha...@phatrasecurities.com



[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function with grouped columns

2010-01-29 Thread Peter Ehlers

Try this:

y <- c(v1, v2, v3, v4)
rowf <- gl(2, 1, 16)
colf <- gl(2, 8, 16, labels=1:0)
dat <- data.frame(y)
aggregate(dat[1], list(Row=rowf, Col=colf), mean)

 -Peter Ehlers

Jack Siegrist wrote:

I have a data set of many rows and many columns in which both the rows and
the columns have associated grouping factors.

Is there a way to do what 'aggregate' does but in the other dimension?

The way I have been doing this is to use 'aggregate' on the data in the
usual way and then rotate the result and apply 'aggregate' again. This
works but is a little messy and I was wondering if there is some built-in
way to do this easier.

An example of what I have been doing is below.

#Four observations of four variables
v1 <- c(1, 8, 5, 3)
v2 <- c(5, 5, 6, 5)
v3 <- c(3, 2, 9, 4)
v4 <- c(4, 1, 1, 1)

myData <- data.frame(v1=v1, v2=v2, v3=v3, v4=v4)
myData

#The observations have either property 1 or property 2
rowFactor <- data.frame(RowTraits=factor(c(1, 2, 1, 2)))
rowFactor

#The variables have a property that is either present or absent
colFactor <- data.frame(ColTraits=factor(c(1, 1, 0, 0)))
colFactor

#Getting the means for the columns by row groups is easy
MeanByRowTraits <- aggregate (myData, rowFactor[1], mean)
MeanByRowTraits

#But now to get the means for the rows by column groups is awkward
rotateData <- data.frame(t(MeanByRowTraits[2:5]))
colnames(rotateData) <- c(levels(rowFactor[,1]))
rotateData

#This is the kind of result I want in the end
aggregate (rotateData, colFactor[1], mean)



--
Peter Ehlers
University of Calgary

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function with grouped columns

2010-01-28 Thread Jack Siegrist
I have a data set of many rows and many columns in which both the rows and
the columns have associated grouping factors.

Is there a way to do what 'aggregate' does but in the other dimension?

The way I have been doing this is to use 'aggregate' on the data in the
usual way and then rotate the result and apply 'aggregate' again. This
works but is a little messy and I was wondering if there is some built-in
way to do this easier.

An example of what I have been doing is below.

#Four observations of four variables
v1 <- c(1, 8, 5, 3)
v2 <- c(5, 5, 6, 5)
v3 <- c(3, 2, 9, 4)
v4 <- c(4, 1, 1, 1)

myData <- data.frame(v1=v1, v2=v2, v3=v3, v4=v4)
myData

#The observations have either property 1 or property 2
rowFactor <- data.frame(RowTraits=factor(c(1, 2, 1, 2)))
rowFactor

#The variables have a property that is either present or absent
colFactor <- data.frame(ColTraits=factor(c(1, 1, 0, 0)))
colFactor

#Getting the means for the columns by row groups is easy
MeanByRowTraits <- aggregate (myData, rowFactor[1], mean)
MeanByRowTraits

#But now to get the means for the rows by column groups is awkward
rotateData <- data.frame(t(MeanByRowTraits[2:5]))
colnames(rotateData) <- c(levels(rowFactor[,1]))
rotateData

#This is the kind of result I want in the end
aggregate (rotateData, colFactor[1], mean)

-- 
Jack Siegrist
Graduate Program in Ecology & Evolution,
and Department of Ecology, Evolution, & Natural Resources,
Rutgers University, New Brunswick, NJ 08901

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function across two variables by mult factors

2009-09-16 Thread Gabor Grothendieck
Try this:

transform(testDF, value = as.numeric(paste(round(abs(x)),
round(abs(y)), sep = ".")))


On Wed, Sep 16, 2009 at 3:22 PM, Jon Loehrke  wrote:
> Greetings,
>
> I am attempting to run a function, which produces a vector and
> requires two input variables, across two nested factor levels.  I can
> do this using by(X, list(factor1, factor2), function), however I
> haven't found a simple way to extract the list output into an
> organized vector form.  I can do this using nested loops but it isn't
> exactly an optimal approach.
>
> Thank you for any and all suggestions.  Jon
>
> # example data frame
> testDF<-data.frame(
>        x=rnorm(12),
>        y=rnorm(12),
>        f1=gl(3,4),
>        f2=gl(2,2,12))
>
> # example function [trivial]
> testFun<-function(x){
>        X<-abs(x[,1]);
>        Y<-abs(x[,2]);
>        as.numeric(     paste(round(X), round(Y), sep='.'))
>        }
>
> # apply by factor levels but hard to extract values
> by(testDF[,1:2], list(testDF$f1, testDF$f2), testFun)
>
> # Loop works, but not efficient for large datasets
> testDF$value<-NA
> for(i in levels(testDF$f1)){
>        for(j in levels(testDF$f2)){
>                testDF[testDF$f1==i & 
> testDF$f2==j,]$value<-testFun(testDF[testDF
> $f1==i & testDF$f2==j,1:2])
>                }
>        }
> testDF
> sessionInfo()
> #R version 2.9.1 Patched (2009-08-07 r49093)
> #i386-apple-darwin8.11.1
> #
> #locale:
> #en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8
> #
> #attached base packages:
> #[1] stats     graphics  grDevices utils     datasets  methods   base
>
>
> Jon Loehrke
> Graduate Research Assistant
> Department of Fisheries Oceanography
> School for Marine Science and Technology
> University of Massachusetts
> 200 Mill Road, Suite 325
> Fairhaven, MA 02719
> jloeh...@umassd.edu
> T 508-910-6393
> F 508-910-6396
>
>
>        [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function across two variables by mult factors

2009-09-16 Thread Jorge Ivan Velez
Hi Jon,
Here is a suggestion:

foo <- function(x) as.numeric( paste( abs( round( x ) ), collapse = "." ) )
testDF$value <- apply( testDF[,1:2], 1, foo )
testDF

HTH,
Jorge


On Wed, Sep 16, 2009 at 3:22 PM, Jon Loehrke  wrote:

> Greetings,
>
> I am attempting to run a function, which produces a vector and
> requires two input variables, across two nested factor levels.  I can
> do this using by(X, list(factor1, factor2), function), however I
> haven't found a simple way to extract the list output into an
> organized vector form.  I can do this using nested loops but it isn't
> exactly an optimal approach.
>
> Thank you for any and all suggestions.  Jon
>
> # example data frame
> testDF<-data.frame(
>x=rnorm(12),
>y=rnorm(12),
>f1=gl(3,4),
>f2=gl(2,2,12))
>
> # example function [trivial]
> testFun<-function(x){
>X<-abs(x[,1]);
>Y<-abs(x[,2]);
>as.numeric( paste(round(X), round(Y), sep='.'))
>}
>
> # apply by factor levels but hard to extract values
> by(testDF[,1:2], list(testDF$f1, testDF$f2), testFun)
>
> # Loop works, but not efficient for large datasets
> testDF$value<-NA
> for(i in levels(testDF$f1)){
>for(j in levels(testDF$f2)){
>testDF[testDF$f1==i &
> testDF$f2==j,]$value<-testFun(testDF[testDF
> $f1==i & testDF$f2==j,1:2])
>}
>}
> testDF
> sessionInfo()
> #R version 2.9.1 Patched (2009-08-07 r49093)
> #i386-apple-darwin8.11.1
> #
> #locale:
> #en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8
> #
> #attached base packages:
> #[1] stats graphics  grDevices utils datasets  methods   base
>
>
> Jon Loehrke
> Graduate Research Assistant
> Department of Fisheries Oceanography
> School for Marine Science and Technology
> University of Massachusetts
> 200 Mill Road, Suite 325
> Fairhaven, MA 02719
> jloeh...@umassd.edu
> T 508-910-6393
> F 508-910-6396
>
>
>[[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function across two variables by mult factors

2009-09-16 Thread Erik Iverson
One correction below, 

---snip---

> >
> > # example data frame
> > testDF<-data.frame(
> > x=rnorm(12),
> > y=rnorm(12),
> > f1=gl(3,4),
> > f2=gl(2,2,12))
> >
> 
> Try this using lapply, split, mapply?  Maybe it is in a nicer output
> object for you?
> 
> testFun2 <- function(x, y) {
>   X <- abs(x);
>   Y <- abs(y);
>   as.numeric(paste(round(X), round(Y), sep='.'))
> }
> 
> lapply(split(testDF, list(testDF$f1, testDF$f2)),
>function(x) mapply(testFun2, x[1], x[2]))
> 

Or use "list indexing" in the mapply call to get a vector, in this case at 
least...

lapply(split(testDF, list(testDF$f1, testDF$f2)),
   function(x) mapply(testFun2, x[[1]], x[[2]]))

---snip---

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function across two variables by mult factors

2009-09-16 Thread Erik Iverson
Hello, 

> -Original Message-
> From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org]
> On Behalf Of Jon Loehrke
> Sent: Wednesday, September 16, 2009 2:23 PM
> To: r-help@r-project.org
> Subject: [R] apply function across two variables by mult factors
> 
> Greetings,
> 
> I am attempting to run a function, which produces a vector and
> requires two input variables, across two nested factor levels.  I can
> do this using by(X, list(factor1, factor2), function), however I
> haven't found a simple way to extract the list output into an
> organized vector form.  I can do this using nested loops but it isn't
> exactly an optimal approach.
> 
> Thank you for any and all suggestions.  Jon
> 
> # example data frame
> testDF<-data.frame(
>   x=rnorm(12),
>   y=rnorm(12),
>   f1=gl(3,4),
>   f2=gl(2,2,12))
> 

Try this using lapply, split, mapply?  Maybe it is in a nicer output object for 
you?  

testFun2 <- function(x, y) {
  X <- abs(x);
  Y <- abs(y);
  as.numeric(paste(round(X), round(Y), sep='.'))
}

lapply(split(testDF, list(testDF$f1, testDF$f2)),
   function(x) mapply(testFun2, x[1], x[2]))



> # example function [trivial]
> testFun<-function(x){
>   X<-abs(x[,1]);
>   Y<-abs(x[,2]);
>   as.numeric( paste(round(X), round(Y), sep='.'))
>   }
> 
> # apply by factor levels but hard to extract values
> by(testDF[,1:2], list(testDF$f1, testDF$f2), testFun)
> 
> # Loop works, but not efficient for large datasets
> testDF$value<-NA
> for(i in levels(testDF$f1)){
>   for(j in levels(testDF$f2)){
>   testDF[testDF$f1==i & testDF$f2==j,]$value<-
> testFun(testDF[testDF
> $f1==i & testDF$f2==j,1:2])
>   }
>   }
> testDF
> sessionInfo()
> #R version 2.9.1 Patched (2009-08-07 r49093)
> #i386-apple-darwin8.11.1
> #
> #locale:
> #en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8
> #
> #attached base packages:
> #[1] stats graphics  grDevices utils datasets  methods   base
> 
> 
> Jon Loehrke
> Graduate Research Assistant
> Department of Fisheries Oceanography
> School for Marine Science and Technology
> University of Massachusetts
> 200 Mill Road, Suite 325
> Fairhaven, MA 02719
> jloeh...@umassd.edu
> T 508-910-6393
> F 508-910-6396
> 
> 
>   [[alternative HTML version deleted]]
> 
> __
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function across two variables by mult factors

2009-09-16 Thread Jon Loehrke
Greetings,

I am attempting to run a function, which produces a vector and  
requires two input variables, across two nested factor levels.  I can  
do this using by(X, list(factor1, factor2), function), however I  
haven't found a simple way to extract the list output into an  
organized vector form.  I can do this using nested loops but it isn't  
exactly an optimal approach.

Thank you for any and all suggestions.  Jon

# example data frame
testDF<-data.frame(
x=rnorm(12),
y=rnorm(12),
f1=gl(3,4),
f2=gl(2,2,12))

# example function [trivial]
testFun<-function(x){
X<-abs(x[,1]);
Y<-abs(x[,2]);
as.numeric( paste(round(X), round(Y), sep='.'))
}

# apply by factor levels but hard to extract values
by(testDF[,1:2], list(testDF$f1, testDF$f2), testFun)

# Loop works, but not efficient for large datasets
testDF$value<-NA
for(i in levels(testDF$f1)){
for(j in levels(testDF$f2)){
testDF[testDF$f1==i & 
testDF$f2==j,]$value<-testFun(testDF[testDF 
$f1==i & testDF$f2==j,1:2])
}
}
testDF
sessionInfo()
#R version 2.9.1 Patched (2009-08-07 r49093)
#i386-apple-darwin8.11.1
#
#locale:
#en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8
#
#attached base packages:
#[1] stats graphics  grDevices utils datasets  methods   base


Jon Loehrke
Graduate Research Assistant
Department of Fisheries Oceanography
School for Marine Science and Technology
University of Massachusetts
200 Mill Road, Suite 325
Fairhaven, MA 02719
jloeh...@umassd.edu
T 508-910-6393
F 508-910-6396


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread Paulo Eduardo Cardoso
Yes, mean of a one element object is meanless, but I'm trying to avoid a
ifelse in the sentence.
The result of mean values of x and y is added at each loop to a data.frame
(or any other object that could speed up the loop.



2009/8/3 ONKELINX, Thierry 

> Dear Paulo,
>
> Your object is a named vector. Apply() and colMeans() only work on
> matrices and dataframes. So you need to convert the vector to a matrix
> or data.frame. See the example below. Please not that calculating the
> mean of one element is a waiste of time.
>
> # a named numerical vector
> object <- c(x = 670, y = 314)
> str(object)
> class(object)
>
> #a data frame with two numerical vectors.
> object2 <- data.frame(x = 670, y = 314)
> str(object2)
> class(object2)
> colMeans(object2)
>
> HTH,
>
> Thierry
>
>
> 
> 
> ir. Thierry Onkelinx
> Instituut voor natuur- en bosonderzoek / Research Institute for Nature
> and Forest
> Cel biometrie, methodologie en kwaliteitszorg / Section biometrics,
> methodology and quality assurance
> Gaverstraat 4
> 9500 Geraardsbergen
> Belgium
> tel. + 32 54/436 185
> thierry.onkel...@inbo.be
> www.inbo.be
>
> To call in the statistician after the experiment is done may be no more
> than asking him to perform a post-mortem examination: he may be able to
> say what the experiment died of.
> ~ Sir Ronald Aylmer Fisher
>
> The plural of anecdote is not data.
> ~ Roger Brinner
>
> The combination of some data and an aching desire for an answer does not
> ensure that a reasonable answer can be extracted from a given body of
> data.
> ~ John Tukey
>
> -Oorspronkelijk bericht-
> Van: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org]
> Namens Paulo Eduardo Cardoso
> Verzonden: maandag 3 augustus 2009 16:19
> Aan: David Winsemius
> CC: [R]
> Onderwerp: Re: [R] apply function to named numeric object
>
> Both objects are numeric, but they differ in structure and I don't know
> how to handle both with a single function to get means.
> When I try to apply colMeans to a named numeric object like this:
>
> Named num [1:2] 670 314
>  - attr(*, "names")= chr [1:2] "x" "y"
>
> I get the error messages:
>
> Error in colMeans(centroid) :
>  'x' must be an array of at least two dimensions
>
> and apply(object,2,mean)
>
> Error in apply(object, 2, mean) : dim(X) must have a positive length
>
> There are something very basic that I'm missing.
>
> 2009/8/3 David Winsemius 
>
> >
> > On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:
> >
> > Thanks. Works
> > A doubt.
> >
> > I asked that because I have a loop that can generate objects like that
>
> > or this one
> >
> >
> > str(object)
> > Named num [1:2] 670 314
> >  - attr(*, "names")= chr [1:2] "x" "y"
> >
> > To avoid using a ifelse() to calculate means of x and y, I'd like a
> > function that handle with this named numeric object and that list. Any
>
> > chance of do it with a single function?
> >
> >
> > I do not see any list object. Lists and arrays (of which the two
> > dimensional ones are of type "matrix") are quite different basic data
> > structures in R. If you interchange the use of those terms you will
> > not get useful replies from R users. Those two object both appear to
> > be matrices and both should be handled by those functions.
> >
> >
> > 2009/8/3 David Winsemius 
> >
> >>
> >> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
> >>
> >>  Maybe a very basic question.
> >>> How can I get mean of a object like this
> >>>
> >>>  str(object)
> >>>>
> >>> num [1:53, 1:2] 734 734 736 734 736 ...
> >>> - attr(*, "dimnames")=List of 2
> >>>  ..$ : NULL
> >>>  ..$ : chr [1:2] "x" "y"
> >>>
> >>> I want the mean of both x and y
> >>>
> >>
> >> apply(object, 2, mean)
> >>
> >> or...
> >>
> >> colMeans(object)  # which will be faster
> >>
> >>
> >>  ___
> >>> Paulo E. Cardoso
> >>>
> >>>[[alternative HTML version deleted]]
> >>>
> >>> __
> >>>
> >>
> >
> > David Winsemius, MD
> > Heritage Laboratories
> > West Hartford

Re: [R] apply function to named numeric object

2009-08-03 Thread ONKELINX, Thierry
Dear Paulo,

Your object is a named vector. Apply() and colMeans() only work on
matrices and dataframes. So you need to convert the vector to a matrix
or data.frame. See the example below. Please not that calculating the
mean of one element is a waiste of time.

# a named numerical vector
object <- c(x = 670, y = 314)
str(object)
class(object)

#a data frame with two numerical vectors.
object2 <- data.frame(x = 670, y = 314)
str(object2)
class(object2)
colMeans(object2)

HTH,

Thierry




ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek / Research Institute for Nature
and Forest
Cel biometrie, methodologie en kwaliteitszorg / Section biometrics,
methodology and quality assurance
Gaverstraat 4
9500 Geraardsbergen
Belgium
tel. + 32 54/436 185
thierry.onkel...@inbo.be
www.inbo.be

To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to
say what the experiment died of.
~ Sir Ronald Aylmer Fisher

The plural of anecdote is not data.
~ Roger Brinner

The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of
data.
~ John Tukey

-Oorspronkelijk bericht-
Van: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org]
Namens Paulo Eduardo Cardoso
Verzonden: maandag 3 augustus 2009 16:19
Aan: David Winsemius
CC: [R]
Onderwerp: Re: [R] apply function to named numeric object

Both objects are numeric, but they differ in structure and I don't know
how to handle both with a single function to get means.
When I try to apply colMeans to a named numeric object like this:

Named num [1:2] 670 314
 - attr(*, "names")= chr [1:2] "x" "y"

I get the error messages:

Error in colMeans(centroid) :
  'x' must be an array of at least two dimensions

and apply(object,2,mean)

Error in apply(object, 2, mean) : dim(X) must have a positive length

There are something very basic that I'm missing.

2009/8/3 David Winsemius 

>
> On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:
>
> Thanks. Works
> A doubt.
>
> I asked that because I have a loop that can generate objects like that

> or this one
>
>
> str(object)
> Named num [1:2] 670 314
>  - attr(*, "names")= chr [1:2] "x" "y"
>
> To avoid using a ifelse() to calculate means of x and y, I'd like a 
> function that handle with this named numeric object and that list. Any

> chance of do it with a single function?
>
>
> I do not see any list object. Lists and arrays (of which the two 
> dimensional ones are of type "matrix") are quite different basic data 
> structures in R. If you interchange the use of those terms you will 
> not get useful replies from R users. Those two object both appear to 
> be matrices and both should be handled by those functions.
>
>
> 2009/8/3 David Winsemius 
>
>>
>> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>>
>>  Maybe a very basic question.
>>> How can I get mean of a object like this
>>>
>>>  str(object)
>>>>
>>> num [1:53, 1:2] 734 734 736 734 736 ...
>>> - attr(*, "dimnames")=List of 2
>>>  ..$ : NULL
>>>  ..$ : chr [1:2] "x" "y"
>>>
>>> I want the mean of both x and y
>>>
>>
>> apply(object, 2, mean)
>>
>> or...
>>
>> colMeans(object)  # which will be faster
>>
>>
>>  ___
>>> Paulo E. Cardoso
>>>
>>>[[alternative HTML version deleted]]
>>>
>>> __
>>>
>>
>
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
>
>


--
___
Paulo E. Cardoso

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Dit bericht en eventuele bijlagen geven enkel de visie van de schrijver weer 
en binden het INBO onder geen enkel beding, zolang dit bericht niet bevestigd is
door een geldig ondertekend document. The views expressed in  this message 
and any annex are purely those of the writer and may not be regarded as stating 
an official position of INBO, as long as the message is not confirmed by a duly 
signed document.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread Paulo Eduardo Cardoso
The objects are
> centroid
x y
669.5 313.5
> str(centroid)
 Named num [1:2] 670 314
 - attr(*, "names")= chr [1:2] "x" "y"

or

> centroid
 x y
[1,] 659.5 472.5
[2,] 659.5 473.5
> str(centroid)
 num [1:2, 1:2] 660 660 472 474
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "x" "y"


I hope this help to clarify the objects I'm getting with the loop.


2009/8/3 David Winsemius 

> So you need to show us how you made the second object. (The Posting Guide's
> phrase "reproducible code" is hereby invoked.)
>
> On Aug 3, 2009, at 10:18 AM, Paulo Eduardo Cardoso wrote:
>
> Both objects are numeric, but they differ in structure and I don't know how
> to handle both with a single function to get means.
> When I try to apply colMeans to a named numeric object like this:
>
> Named num [1:2] 670 314
>  - attr(*, "names")= chr [1:2] "x" "y"
>
> I get the error messages:
>
> Error in colMeans(centroid) :
>   'x' must be an array of at least two dimensions
>
> and apply(object,2,mean)
>
> Error in apply(object, 2, mean) : dim(X) must have a positive length
>
> There are something very basic that I'm missing.
>
> 2009/8/3 David Winsemius 
>
>>
>> On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:
>>
>> Thanks. Works
>> A doubt.
>>
>> I asked that because I have a loop that can generate objects like that or
>> this one
>>
>>
>> str(object)
>> Named num [1:2] 670 314
>>  - attr(*, "names")= chr [1:2] "x" "y"
>>
>> To avoid using a ifelse() to calculate means of x and y, I'd like a
>> function that handle with this named numeric object and that list. Any
>> chance of do it with a single function?
>>
>>
>> I do not see any list object. Lists and arrays (of which the two
>> dimensional ones are of type "matrix") are quite different basic data
>> structures in R. If you interchange the use of those terms you will not get
>> useful replies from R users. Those two object both appear to be matrices and
>> both should be handled by those functions.
>>
>>
>> 2009/8/3 David Winsemius 
>>
>>>
>>> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>>>
>>>  Maybe a very basic question.
 How can I get mean of a object like this

  str(object)
>
 num [1:53, 1:2] 734 734 736 734 736 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "x" "y"

 I want the mean of both x and y

>>>
>>> apply(object, 2, mean)
>>>
>>> or...
>>>
>>> colMeans(object)  # which will be faster
>>>
>>>
>>>
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
>
>


-- 
___
Paulo E. Cardoso

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread David Winsemius
That may just be a vector with two elements, so functions designed for  
matrices are not going to "work". Why are you taking means of such  
small data objects anyway?

 > obj <- c(x=640, y=410)
 > obj
   x   y
640 410
 > str(obj)
  Named num [1:2] 640 410
  - attr(*, "names")= chr [1:2] "x" "y"
 > mean(obj)
[1] 525


On Aug 3, 2009, at 10:18 AM, Paulo Eduardo Cardoso wrote:

> Both objects are numeric, but they differ in structure and I don't  
> know how to handle both with a single function to get means.
>
> When I try to apply colMeans to a named numeric object like this:
>> Named num [1:2] 670 314
>>  - attr(*, "names")= chr [1:2] "x" "y"
>
> I get the error messages:
>
> Error in colMeans(centroid) :
>   'x' must be an array of at least two dimensions
>
> and apply(object,2,mean)
>
> Error in apply(object, 2, mean) : dim(X) must have a positive length
>
> There are something very basic that I'm missing.
>
> 2009/8/3 David Winsemius 
>
> On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:
>
>> Thanks. Works
>>
>> A doubt.
>>
>> I asked that because I have a loop that can generate objects like  
>> that or this one
>>
>>
>> str(object)
>> Named num [1:2] 670 314
>>  - attr(*, "names")= chr [1:2] "x" "y"
>>
>> To avoid using a ifelse() to calculate means of x and y, I'd like a  
>> function that handle with this named numeric object and that list.  
>> Any chance of do it with a single function?
>
> I do not see any list object. Lists and arrays (of which the two  
> dimensional ones are of type "matrix") are quite different basic  
> data structures in R. If you interchange the use of those terms you  
> will not get useful replies from R users. Those two object both  
> appear to be matrices and both should be handled by those functions.
>
>
>> 2009/8/3 David Winsemius 
>>
>> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>>
>> Maybe a very basic question.
>> How can I get mean of a object like this
>>
>> str(object)
>> num [1:53, 1:2] 734 734 736 734 736 ...
>> - attr(*, "dimnames")=List of 2
>>  ..$ : NULL
>>  ..$ : chr [1:2] "x" "y"
>>
>> I want the mean of both x and y
>>
>> apply(object, 2, mean)
>>
>> or...
>>
>> colMeans(object)  # which will be faster
>>
>>
>> ___
>> Paulo E. Cardoso
>>
>>[[alternative HTML version deleted]]
>>
>> __
>>
>
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
>
>
>
>
> -- 
> ___
> Paulo E. Cardoso

David Winsemius, MD
Heritage Laboratories
West Hartford, CT


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread David Winsemius
So you need to show us how you made the second object. (The Posting  
Guide's phrase "reproducible code" is hereby invoked.)


On Aug 3, 2009, at 10:18 AM, Paulo Eduardo Cardoso wrote:

> Both objects are numeric, but they differ in structure and I don't  
> know how to handle both with a single function to get means.
>
> When I try to apply colMeans to a named numeric object like this:
>> Named num [1:2] 670 314
>>  - attr(*, "names")= chr [1:2] "x" "y"
>
> I get the error messages:
>
> Error in colMeans(centroid) :
>   'x' must be an array of at least two dimensions
>
> and apply(object,2,mean)
>
> Error in apply(object, 2, mean) : dim(X) must have a positive length
>
> There are something very basic that I'm missing.
>
> 2009/8/3 David Winsemius 
>
> On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:
>
>> Thanks. Works
>>
>> A doubt.
>>
>> I asked that because I have a loop that can generate objects like  
>> that or this one
>>
>>
>> str(object)
>> Named num [1:2] 670 314
>>  - attr(*, "names")= chr [1:2] "x" "y"
>>
>> To avoid using a ifelse() to calculate means of x and y, I'd like a  
>> function that handle with this named numeric object and that list.  
>> Any chance of do it with a single function?
>
> I do not see any list object. Lists and arrays (of which the two  
> dimensional ones are of type "matrix") are quite different basic  
> data structures in R. If you interchange the use of those terms you  
> will not get useful replies from R users. Those two object both  
> appear to be matrices and both should be handled by those functions.
>
>
>> 2009/8/3 David Winsemius 
>>
>> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>>
>> Maybe a very basic question.
>> How can I get mean of a object like this
>>
>> str(object)
>> num [1:53, 1:2] 734 734 736 734 736 ...
>> - attr(*, "dimnames")=List of 2
>>  ..$ : NULL
>>  ..$ : chr [1:2] "x" "y"
>>
>> I want the mean of both x and y
>>
>> apply(object, 2, mean)
>>
>> or...
>>
>> colMeans(object)  # which will be faster
>>
>>

David Winsemius, MD
Heritage Laboratories
West Hartford, CT


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread Paulo Eduardo Cardoso
Both objects are numeric, but they differ in structure and I don't know how
to handle both with a single function to get means.
When I try to apply colMeans to a named numeric object like this:

Named num [1:2] 670 314
 - attr(*, "names")= chr [1:2] "x" "y"

I get the error messages:

Error in colMeans(centroid) :
  'x' must be an array of at least two dimensions

and apply(object,2,mean)

Error in apply(object, 2, mean) : dim(X) must have a positive length

There are something very basic that I'm missing.

2009/8/3 David Winsemius 

>
> On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:
>
> Thanks. Works
> A doubt.
>
> I asked that because I have a loop that can generate objects like that or
> this one
>
>
> str(object)
> Named num [1:2] 670 314
>  - attr(*, "names")= chr [1:2] "x" "y"
>
> To avoid using a ifelse() to calculate means of x and y, I'd like a
> function that handle with this named numeric object and that list. Any
> chance of do it with a single function?
>
>
> I do not see any list object. Lists and arrays (of which the two
> dimensional ones are of type "matrix") are quite different basic data
> structures in R. If you interchange the use of those terms you will not get
> useful replies from R users. Those two object both appear to be matrices and
> both should be handled by those functions.
>
>
> 2009/8/3 David Winsemius 
>
>>
>> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>>
>>  Maybe a very basic question.
>>> How can I get mean of a object like this
>>>
>>>  str(object)

>>> num [1:53, 1:2] 734 734 736 734 736 ...
>>> - attr(*, "dimnames")=List of 2
>>>  ..$ : NULL
>>>  ..$ : chr [1:2] "x" "y"
>>>
>>> I want the mean of both x and y
>>>
>>
>> apply(object, 2, mean)
>>
>> or...
>>
>> colMeans(object)  # which will be faster
>>
>>
>>  ___
>>> Paulo E. Cardoso
>>>
>>>[[alternative HTML version deleted]]
>>>
>>> __
>>>
>>
>
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
>
>


-- 
___
Paulo E. Cardoso

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread David Winsemius

On Aug 3, 2009, at 9:52 AM, Paulo Eduardo Cardoso wrote:

> Thanks. Works
>
> A doubt.
>
> I asked that because I have a loop that can generate objects like  
> that or this one
>
>
> str(object)
> Named num [1:2] 670 314
>  - attr(*, "names")= chr [1:2] "x" "y"
>
> To avoid using a ifelse() to calculate means of x and y, I'd like a  
> function that handle with this named numeric object and that list.  
> Any chance of do it with a single function?

I do not see any list object. Lists and arrays (of which the two  
dimensional ones are of type "matrix") are quite different basic data  
structures in R. If you interchange the use of those terms you will  
not get useful replies from R users. Those two object both appear to  
be matrices and both should be handled by those functions.


> 2009/8/3 David Winsemius 
>
> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>
> Maybe a very basic question.
> How can I get mean of a object like this
>
> str(object)
> num [1:53, 1:2] 734 734 736 734 736 ...
> - attr(*, "dimnames")=List of 2
>  ..$ : NULL
>  ..$ : chr [1:2] "x" "y"
>
> I want the mean of both x and y
>
> apply(object, 2, mean)
>
> or...
>
> colMeans(object)  # which will be faster
>
>
> ___
> Paulo E. Cardoso
>
>[[alternative HTML version deleted]]
>
> __
>

David Winsemius, MD
Heritage Laboratories
West Hartford, CT


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread Paulo Eduardo Cardoso
Thanks. Works
A doubt.

I asked that because I have a loop that can generate objects like that or
this one


str(object)
Named num [1:2] 670 314
 - attr(*, "names")= chr [1:2] "x" "y"

To avoid using a ifelse() to calculate means of x and y, I'd like a function
that handle with this named numeric object and that list. Any chance of do
it with a single function?



2009/8/3 David Winsemius 

>
> On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:
>
>  Maybe a very basic question.
>> How can I get mean of a object like this
>>
>>  str(object)
>>>
>> num [1:53, 1:2] 734 734 736 734 736 ...
>> - attr(*, "dimnames")=List of 2
>>  ..$ : NULL
>>  ..$ : chr [1:2] "x" "y"
>>
>> I want the mean of both x and y
>>
>
> apply(object, 2, mean)
>
> or...
>
> colMeans(object)  # which will be faster
>
>
>  ___
>> Paulo E. Cardoso
>>
>>[[alternative HTML version deleted]]
>>
>> __
>>
>
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
>
>


-- 
___
Paulo E. Cardoso

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function to named numeric object

2009-08-03 Thread David Winsemius


On Aug 3, 2009, at 9:07 AM, Paulo Eduardo Cardoso wrote:


Maybe a very basic question.
How can I get mean of a object like this


str(object)

num [1:53, 1:2] 734 734 736 734 736 ...
- attr(*, "dimnames")=List of 2
 ..$ : NULL
 ..$ : chr [1:2] "x" "y"

I want the mean of both x and y


apply(object, 2, mean)

or...

colMeans(object)  # which will be faster



___
Paulo E. Cardoso

[[alternative HTML version deleted]]

__


David Winsemius, MD
Heritage Laboratories
West Hartford, CT

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function to named numeric object

2009-08-03 Thread Paulo Eduardo Cardoso
Maybe a very basic question.
How can I get mean of a object like this

> str(object)
 num [1:53, 1:2] 734 734 736 734 736 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "x" "y"

I want the mean of both x and y
___
Paulo E. Cardoso

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Apply function

2008-11-11 Thread tedzzx

Hi all

I am manipulating a datafram which has 3 variables.Such as:

1  2  3
4  5  6
.  
.
.
200  210  300

I also has a row index: index=c(100,200,250..300)
I want to find the sums of first 100 rows, then the sum from row 101 to row
200, then row 201 to row 250... the each end row is indicated by the index.

Can I use the apply function to do that? or any other way?

Thanks

Ted


-- 
View this message in context: 
http://www.nabble.com/Apply-function-tp20434042p20434042.html
Sent from the R help mailing list archive at Nabble.com.

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] *apply function for arrays?

2008-05-19 Thread Uwe Ligges



Hesen Peng wrote:

Hi,

Thank you so much for the help. apply does work for the first situation.

For the second situation, I'm currently using:

temp.a<-function(i,j){
  return(G(M[i,],N[j,]))
}
temp.v<-Vectorize(temp.a)
result<-outer(1:nrow(M),1:nrow(N),FUN=temp.v)


Looks pretty good!

Uwe




And I wonder whether there are some other ways to do this.

On Sun, May 18, 2008 at 3:52 PM, Patrick Burns <[EMAIL PROTECTED]> wrote:

You want to use the 'apply' function.  S Poetry
has a chapter on higher dimensional arrays that
may be of use to you.

I don't see a good approach for your second
situation other than a double for loop.  Unless
G is linear, I think all other solutions will be
equivalent to a double for loop, though the
loops may be hidden.


Patrick Burns
[EMAIL PROTECTED]
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Hesen Peng wrote:

Hi all,

I've recently been writing functions which may deal with very large
arrays. And I hope to use *apply functions in the program so that the
code may look nicer and the performance may be better in the following
two situations.

The first situation is:

I'm having an array A with dim(A)==c(m,n,p). And I want to apply a
function F to a group of elements in A like:

1) F is applied to every group of elements like A[i,j,] for all i and j.
or
2) F is applied to every group of elements like A[i,,] for all i, or
A[,j,] for all j.

The result is then expected to be a m*n-dimensional matrix

I'm currently using for loops to do this but I guess there maybe some
*apply functions for arrays which may accomplish this task.

The second situation is:

I'm having two matrix M and N and a function G, which is a function of
two arrays. I want to form a matrix R with dim(R)==c(nrow(M),nrow(N)),
and R[i,j] <- G(M[i,], N[j,]). And I wonder whether I may use some
functions like outer to the matrix.

Thank you very much and have a nice weekend.








__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] *apply function for arrays?

2008-05-18 Thread Hesen Peng
Hi,

Thank you so much for the help. apply does work for the first situation.

For the second situation, I'm currently using:

temp.a<-function(i,j){
  return(G(M[i,],N[j,]))
}
temp.v<-Vectorize(temp.a)
result<-outer(1:nrow(M),1:nrow(N),FUN=temp.v)

And I wonder whether there are some other ways to do this.

On Sun, May 18, 2008 at 3:52 PM, Patrick Burns <[EMAIL PROTECTED]> wrote:
> You want to use the 'apply' function.  S Poetry
> has a chapter on higher dimensional arrays that
> may be of use to you.
>
> I don't see a good approach for your second
> situation other than a double for loop.  Unless
> G is linear, I think all other solutions will be
> equivalent to a double for loop, though the
> loops may be hidden.
>
>
> Patrick Burns
> [EMAIL PROTECTED]
> +44 (0)20 8525 0696
> http://www.burns-stat.com
> (home of S Poetry and "A Guide for the Unwilling S User")
>
> Hesen Peng wrote:
>>
>> Hi all,
>>
>> I've recently been writing functions which may deal with very large
>> arrays. And I hope to use *apply functions in the program so that the
>> code may look nicer and the performance may be better in the following
>> two situations.
>>
>> The first situation is:
>>
>> I'm having an array A with dim(A)==c(m,n,p). And I want to apply a
>> function F to a group of elements in A like:
>>
>> 1) F is applied to every group of elements like A[i,j,] for all i and j.
>> or
>> 2) F is applied to every group of elements like A[i,,] for all i, or
>> A[,j,] for all j.
>>
>> The result is then expected to be a m*n-dimensional matrix
>>
>> I'm currently using for loops to do this but I guess there maybe some
>> *apply functions for arrays which may accomplish this task.
>>
>> The second situation is:
>>
>> I'm having two matrix M and N and a function G, which is a function of
>> two arrays. I want to form a matrix R with dim(R)==c(nrow(M),nrow(N)),
>> and R[i,j] <- G(M[i,], N[j,]). And I wonder whether I may use some
>> functions like outer to the matrix.
>>
>> Thank you very much and have a nice weekend.
>>
>>
>



-- 
彭河森 Hesen Peng
http://hesen.peng.googlepages.com/
__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] *apply function for arrays?

2008-05-18 Thread Uwe Ligges



Hesen Peng wrote:

Hi all,

I've recently been writing functions which may deal with very large
arrays. And I hope to use *apply functions in the program so that the
code may look nicer and the performance may be better in the following
two situations.

The first situation is:

I'm having an array A with dim(A)==c(m,n,p). And I want to apply a
function F to a group of elements in A like:

1) F is applied to every group of elements like A[i,j,] for all i and j.
or
2) F is applied to every group of elements like A[i,,] for all i, or
A[,j,] for all j.


Well, apply() itself does the job.

Uwe Ligges






The result is then expected to be a m*n-dimensional matrix

I'm currently using for loops to do this but I guess there maybe some
*apply functions for arrays which may accomplish this task.

The second situation is:

I'm having two matrix M and N and a function G, which is a function of
two arrays. I want to form a matrix R with dim(R)==c(nrow(M),nrow(N)),
and R[i,j] <- G(M[i,], N[j,]). And I wonder whether I may use some
functions like outer to the matrix.

Thank you very much and have a nice weekend.



__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] *apply function for arrays?

2008-05-17 Thread Hesen Peng
Hi all,

I've recently been writing functions which may deal with very large
arrays. And I hope to use *apply functions in the program so that the
code may look nicer and the performance may be better in the following
two situations.

The first situation is:

I'm having an array A with dim(A)==c(m,n,p). And I want to apply a
function F to a group of elements in A like:

1) F is applied to every group of elements like A[i,j,] for all i and j.
or
2) F is applied to every group of elements like A[i,,] for all i, or
A[,j,] for all j.

The result is then expected to be a m*n-dimensional matrix

I'm currently using for loops to do this but I guess there maybe some
*apply functions for arrays which may accomplish this task.

The second situation is:

I'm having two matrix M and N and a function G, which is a function of
two arrays. I want to form a matrix R with dim(R)==c(nrow(M),nrow(N)),
and R[i,j] <- G(M[i,], N[j,]). And I wonder whether I may use some
functions like outer to the matrix.

Thank you very much and have a nice weekend.

-- 
彭河森 Hesen Peng
http://hesen.peng.googlepages.com/
__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] apply function

2008-05-15 Thread Berwin A Turlach
G'day Shuba,

On Thu, 15 May 2008 12:18:58 +0530
"Shubha Vishwanath Karanth" <[EMAIL PROTECTED]> wrote:

> Getting a strange result using ?apply. Please look into the below
> codes:
>
> d=data.frame(a=c(1,2,3),b=c("A","B","C"),c=c(TRUE,FALSE,FALSE),d=c(T,F,F))
> 
> > class(d[,1])
> 
> [1] "numeric"
> 
> > class(d[,2])
> 
> [1] "factor"
> 
> > class(d[,3])
> 
> [1] "logical"
> 
> > class(d[,4])
> 
> [1] "logical"
> 
> > apply(d,2,class)
> 
>   a   b   c   d 
> 
> "character" "character" "character" "character" 
[]
> Why is this so? 

?apply
The first argument to apply is an *array*, not a data.frame.  In an
array, all elements have to be of the same type, so when your
data.frame is coerced into an array the target type of the coercion
depends on which components you select.

> How do I get the actual classes of columns of my dataframe d?

Something like:

R> lapply(d, class)
$a
[1] "numeric"

$b
[1] "factor"

$c
[1] "logical"

$d
[1] "logical"

could be used.

HTH.

Best wishes,

Berwin

=== Full address =
Berwin A TurlachTel.: +65 6515 4416 (secr)
Dept of Statistics and Applied Probability+65 6515 6650 (self)
Faculty of Science  FAX : +65 6872 3919   
National University of Singapore 
6 Science Drive 2, Blk S16, Level 7  e-mail: [EMAIL PROTECTED]
Singapore 117546http://www.stat.nus.edu.sg/~statba

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] apply function

2008-05-14 Thread Shubha Vishwanath Karanth
Hi R,

 

Getting a strange result using ?apply. Please look into the below codes:

 

>
d=data.frame(a=c(1,2,3),b=c("A","B","C"),c=c(TRUE,FALSE,FALSE),d=c(T,F,F
))

> class(d[,1])

[1] "numeric"

> class(d[,2])

[1] "factor"

> class(d[,3])

[1] "logical"

> class(d[,4])

[1] "logical"

 

 

> apply(d,2,class)

  a   b   c   d 

"character" "character" "character" "character" 

> apply(d[,c(1,3)],2,class)

a c 

"numeric" "numeric" 

> apply(d[,c(3,4)],2,class)

c d 

"logical" "logical" 

> apply(d[,c(3,2)],2,class)

  c   b 

"character" "character" 

> 

 

 

Why is this so? How do I get the actual classes of columns of my
dataframe d?

 

Thanks,

Shubha

 

This e-mail may contain confidential and/or privileged i...{{dropped:13}}

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.