关于 r:向数据框列表添加新列 | 珊瑚贝

Adding new column to list of data frames


我正在清理我从 excel、大量文件中导入的一些数据,并且在导入期间必须根据文件名的下标创建两个键。这些文件是按国家/地区导入的。我设法将文件导入到单独的数据框中,但在创建新变量时遇到了困难。为简洁起见,我设置了 country=”usa” 和 year=1980。

我的第一个想法是通过过滤模式”USA”来创建环境中存在的数据框的列表。但是,这种风格很差,而且产品似乎是一个与数据框本身没有连接的字符列表。

1
usadflist <- Filter(is.data.frame, mget(ls(pattern=”USA”)))

这是当我转向调整实际导入时,使用 dplyr::mutate(),但是无法指定尚未创建的变量,这是我尝试 cbind() 的时候,如下:

1
2
3
4
5
6
usalist <- list.files(path =”~/Desktop/reports/usa”)

for(i in usalist) {
  assign(paste(i),read_excel(path = paste(“Desktop/reports/usa/”,i,sep=””)))
  cbind(usalist[[i]][country]<-“usa”, usalist[[i]][year]<-1980)
}

给出错误消息:*tmp*[[i]] 中的错误:下标超出范围。

我期望的是每个数据框都会有一个新变量:国家,其值为 “usa”


您是否尝试过类似的方法:

1
2
3
4
5
6
7
8
usalist <- list.files(path =”~/Desktop/reports/usa”)

for(i in 1:length(usalist)){
  df <- read_excel(path = paste(“Desktop/reports/usa/”, usalist[i], sep =””))
  df$country <-“usa”
  df$year <- 1980L
  assign(usalist[i], df); rm(df)
}; rm(i)

没有运行它,所以我不能说我是否没有输入错误。

  • 谢谢@Feakster,这是正确的。使用临时 df 解决了这个问题。下面更正以避免在循环中使用$,i可以直接在循环中命名,并且新变量需要在引号中。 for(i in usalist) { df<- read_excel(path = paste(“Desktop/reports/usa/”,i,sep=””)) df[“country”]<-substr(i,start=1,stop=3) df[“year”] <-substr(i,start=10,stop=13) assign(i,df);rm(df) }


来源:https://www.codenong.com/56855949/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9501.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?