I have several vectors named: aa, bb, ab, ac, etc.
I'd like to use their names ("01","02","03","04", etc) to match the vectors with a df.
But I get an error because names(i)
doesn't work, given that (in case i <- "aa") R reads names("aa")
, instead of: names(aa)
.
How can be solved?
noquote(i)
worked, but not inside names: names(noquote(i))
. This produced an error.
x <- c("aa","bb","ab","ac")
names(x) <- c("01","02","03","04")
for (i in x) {
df[match(names(i), df$ID), i] <- noquote(i)
}
########################################
Example:
df <- data.frame(ID = c("01","02","02","03","03","03"),
var_1 = c(0,0,1,0,0,1),
var_2 = c(0,0,0,0,1,0),
var_3 = c(1,0,0,0,0,0))
aa <- tapply(df$var_1, df$ID, max, na.rm = T)
bb <- tapply(df$var_2, df$ID, max, na.rm = T)
cc <- tapply(df$var_3, df$ID, max, na.rm = T)
In df_2 there's just one rown for each ID and I want to include in df_2 the vectors I created with tapply.
df_2 <- data.frame(ID=c("01","02","03"), age=c(34,12,49))
In order to match exactly the ID I used the following code:
df_2[match(names(aa), df_2$ID), "aa"] <- aa
df_2[match(names(bb), df_2$ID), "bb"] <- bb
df_2[match(names(cc), df_2$ID), "cc"] <- cc
In order to avoid this repetition of code I was trying to use this code (that i wrote at the beginning of the post):
x <- c("aa","bb","cc")
for (i in x) {
df_2[match(names(i), df_2$ID), i] <- noquote(i)
}
but I have a problem with names(i)