本文介绍了R如何循环数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 假设有很多数据帧需要对它们执行相同的操作。例如: 前缀措施 df1 df1 $ gender [df1 $ prefix ==Mrs.]< - F 当相邻行的值是Mrs.时,将创建一个名为gender的指示变量。在R中循环字符串变量的一般方法是从这里改编的函数 as.name()添加以从i删除引号: as。$ c> dflist< -c(df1,df2,df3,df4,df5) 。名称(i)$ gender [as.name(i)$ prefix ==Ms。]< - F} 不幸的是,这是行不通的。有什么建议么?把所有的数据框放到一个列表中,然后循环/ lapply 在他们身上。 dfList dfList< - lapply(dfList,function(df){ df $ gender [df $ prefix ==Mrs.]< - F df }) dfList $ df1 Suppose there are many data frames that need the same operation performed on them. For example: 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"Would create an indicator variable called gender when the value in the adjacent row was "Mrs.". A general way to loop over string variables in R was adapted from here with the function as.name() added to remove the quotes from "i":dflist <- c("df1","df2","df3","df4","df5")for (i in dflist) { as.name(i)$gender[as.name(i)$prefix=="Ms."] <- "F" }Unfortunately this doesn't work. Any suggestions? 解决方案 Put all your data frames into a list, and then loop/lapply over them. It'll be much easier on you in the long run.dfList <- list(df1=df1, df2=df2, ....)dfList <- lapply(dfList, function(df) { df$gender[df$prefix == "Mrs."] <- "F" df})dfList$df1 这篇关于R如何循环数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 08:54