[R] indexing in data frames
arun
smartpink111 at yahoo.com
Fri Aug 10 00:30:17 CEST 2012
HI,
If "b" is also an "element of list, then it would be much easier.
b<-c(1988,1989,1990,1991,1992)
c<-list(c(1985,1982,1984),c(1988,1980),c(1983,1984),c(1988,1998,1993),c(1993,1994,1998))
a<-list(b,c)
names(a)<-c("b","c")
lapply(1:length(a$c),function(x) a$b[x]-a$c[[x]])
[[1]]
[1] 3 6 4
[[2]]
[1] 1 9
[[3]]
[1] 7 6
[[4]]
[1] 3 -7 -2
[[5]]
[1] -1 -2 -6
#2nd case
d<-data.frame(a1=c(1998,1924,1938),b1=c(1942,1938,1944))
a2<-list(d,c)
lapply(1:length(c),function(x) a2$d[,1:2]-a2$c[[x]])
A.K.
----- Original Message -----
From: jimi adams <jadams at american.edu>
To: arun <smartpink111 at yahoo.com>
Cc: R help <r-help at r-project.org>
Sent: Thursday, August 9, 2012 5:42 PM
Subject: Re: [R] indexing in data frames
Thanks. Yes, I got it to work with loops for small data. I was just hoping, given the size of the data.frame (hundreds of thousands) and the length of the lists (varying up to a few hundred) to avoid that if at all possible. Perhaps I'm expecting some behavior that's not feasible?
cheers,
jimi
On 09Aug, 2012, at 17:39 , arun wrote:
> HI,
>
> In the reply I sent, I forgot to add,
>
> anew<-list()#before,
> for(i in 1:length(b1)){
> anew[[i]]<-list()
> anew[[i]]<-b1[[i]]-c[[i]]
> }
>
> A.K.
>
> ----- Original Message -----
> From: jimi adams <jadams at american.edu>
> To: r-help at r-project.org
> Cc:
> Sent: Thursday, August 9, 2012 4:42 PM
> Subject: [R] indexing in data frames
>
> I'm still not fully understanding exactly how R is handling data frames, but am getting closer. Any help with this one will likely go a long way in getting me there. Let's say I have a data frame, let's call it "a". Within that data frame i have two variables, let's call them "b" and "c", where "b" is a single numeric value per observation, while "c" is a LIST of numeric values. What I want to be able to do is perform an operation on each element in "c" by the single element in "b".
>
> So, for example, if I wanted to subtract each element in "c" from the scalar in "b". For example, if i had
>
>> a$b
> [1] 1988
> [2] 1989
> …
> &
>> a$c
> [[1]]
> [1] 1985 1982 1984
> [[2]]
> [1] 1988 1980
> …
>
> I'm looking for a result of:
> a$new
> [[1]]
> [1] 3 6 4
> [[2]]
> [1] 1 9
> …
>
> I've tried a few different things, none of which have the desired result. Any help appreciated.
> thanks!
>
> jimi adams
> Assistant Professor
> Department of Sociology
> American University
> e: jadams at american.edu
> w: jimiadams.com
>
> ______________________________________________
> R-help at 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.
>
More information about the R-help
mailing list