Hope someone can help me on this one for which I have just found a lousy solution on my own: I would like to aggregate (or paste) the labels of four columns ( A
to D
) into a fifth ( dream
) but conditionally, that is only if its numeric value is 2.
Here is my database df
:
id= c(1:12)
A = c(2,NA,NA,2,NA,1,1,1,1,1,NA,2)
B = c(2,1,1,1,2,NA,1,1,1,1,2,1)
C = c(2,1,1,1,2,NA,1,1,1,1,NA,1)
D = c(2,1,1,1,1,1,2,1,1,NA,2,1)
df = data.frame(id,A,B,C,D) ; df
df$A=factor(df$A, labels=c("no", "i saw"))
df$B=factor(df$B, labels=c("no", "someone"))
df$C=factor(df$C, labels=c("no", "sitting"))
df$D=factor(df$D, labels=c("no", "on a cloud")) ; df
Here is below the solution i found, but not so satisfying...
df$dream = ifelse(as.numeric(df$A)!=2, NA, as.character(df$A)) ; df
df$dream = ifelse(as.numeric(df$B)!=2, df$dream, paste(df$dream, as.character(df$B))) ; df
df$dream = ifelse(as.numeric(df$C)!=2, df$dream, paste(df$dream, as.character(df$C))) ; df
df$dream = ifelse(as.numeric(df$D)!=2, df$dream, paste(df$dream, as.character(df$D))) ; df
I am sure there is a straightfoward way to do so, in addition my code doesn't even seem to work this way.. Could someone help me? Thanks
I think it would be easier if you transform you data.frame
in data.table
.
For column B
you can use
dt <- as.data.table(df)
dt[,dream:=ifelse(B==2,"someone",ifelse(B==1,"no",NA))]
And then replicate the same for the rest 3 columns
. I hope this helps
UPDATE
Or maybe you could try this
dt$dream.A <- mapvalues(dt$A,c(1,2),c("no", "i saw"))
This solution will work but you have to declare this vector of values you want to paste from factors.
# init empty result vector
dream <- character(nrow(df))
# values from each column (A-D) you want to paste
values <- c("i saw","someone","sitting", "on a cloud")
# iterate over each row
for(i in seq_len(nrow(df))){
#paste values from each row
dream[i] <- paste(values[which(as.numeric(df[i,-1]) == 2)], collapse=" ")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.