假设有许多数据帧需要对它们执行相同的操作。例如:
prefix <- c("Mrs.","Mrs.","Mr","Dr.","Mrs.","Mr.","Mrs.","Ms","Ms","Mr")
measure <- rnorm(10)
df1 <- data.frame(prefix,measure)
df1$gender[df1$prefix=="Mrs."] <- "F"
当相邻行中的值为“夫人”时,将创建一个称为性别的指示变量。在 R 中循环字符串变量的一般方法是从这里as.name()
改编的,添加了从“i”中删除引号的函数:
dflist <- c("df1","df2","df3","df4","df5")
for (i in dflist) {
as.name(i)$gender[as.name(i)$prefix=="Ms."] <- "F"
}
不幸的是,这不起作用。有什么建议么?