问题
I wanted to create new columns for my data.table based on ratio calculation. The names of my variables are slightly in a standard way so I think there must be a way to easily achieve this in data.table. However I am not able to get how to achieve this. Below is my sample data and code -
set.seed(1200)
ID <- seq(1001,1100)
region <- sample(1:10,100,replace = T)
Q21 <- sample(1:5,100,replace = T)
Q22 <- sample(1:15,100,replace = T)
Q24_LOC_1 <- sample(1:8,100,replace = T)
Q24_LOC_2 <- sample(1:8,100,replace = T)
Q24_LOC_3 <- sample(1:8,100,replace = T)
Q24_LOC_4 <- sample(1:8,100,replace = T)
Q21_PAN <- sample(1:5,100,replace = T)
Q22_PAN <- sample(1:15,100,replace = T)
Q24_LOC_1_PAN <- sample(1:8,100,replace = T)
Q24_LOC_2_PAN <- sample(1:8,100,replace = T)
Q24_LOC_3_PAN <- sample(1:8,100,replace = T)
Q24_LOC_4_PAN <- sample(1:8,100,replace = T)
df1 <- as.data.table(data.frame(ID,region,Q21,Q22,Q24_LOC_1,Q24_LOC_2,Q24_LOC_3,Q24_LOC_4,Q21_PAN,Q22_PAN,Q24_LOC_1_PAN,Q24_LOC_2_PAN,Q24_LOC_3_PAN,Q24_LOC_4_PAN))
col_needed <- c("Q21","Q22","Q24_LOC_1","Q24_LOC_2","Q24_LOC_3","Q24_LOC_4")
check1 <- df1[,Q21_R := mean(Q21,na.rm = T)/mean(Q21_PAN,na.rm = T),by=region]
check1 works for one variable. I was looking for a solution where I can pass all needed variables and get the new variables calculated in a single line. So in this case something like passing col_needed. I tried below code as well -
check2 <- df1[,`:=`(paste0(col_needed,"_R"),(mean(col_needed,na.rm = T)/mean(paste0(col_needed,"_PAN"),na.rm = T))),by=region][]
However this gives me multiple warnings and the result is having all NAs. The warnings are - In mean(col_needed, na.rm = T) : argument is not numeric or logical: returning NA
Can you please suggest where I am going wrong.
回答1:
If I understand correctly, you could do the following:
df1[, paste(col_needed, "R", sep = "_") :=
Map(function(x,y) mean(get(x), na.rm = TRUE)/mean(get(y), na.rm=TRUE),
col_needed,
paste(col_needed, "PAN", sep = "_")),
by=region]
来源:https://stackoverflow.com/questions/49878098/r-data-table-create-new-columns-with-standard-names