r - 使用 R 使用 lapply 将列添加到多个数据帧

标签 r function substring lapply

我想在每一列中添加一个包含年份(在文件名中找到)的列。我花了几个小时用谷歌搜索这个,但无法让它工作。我犯了一些简单的错误吗?

从概念上讲,我正在制作一个文件列表,然后使用 lapply 为列表中的每个文件计算一列。

我正在使用来自人口普查的数据 OnTheMap.新鲜下载。所有文件都这样命名:“points_2013”​​“points_2014”等。使用以下代码读取数据:

library(maptools)
library(sp)
shps <- dir(getwd(), "*.shp")
for (shp in shps) assign(shp, readShapePoints(shp)) 
# the assign function will take the string representing shp
# and turn it into a variable which holds the spatial points data

我的问题与this one 非常相似,只是我没有文件名列表——我只想从文件名中提取列中的条目。 This thread有一个问题,但没有答案。 This person尝试使用 [[ 而不是 $,但没有成功。 This似乎暗示故障可能出在 cbind 与 rbind 中……不确定。我不想输出到 csv,所以 this不完全相关。

This几乎正是我想要做的。根据我的目的调整该示例中的代码会产生以下结果:

dat <- ls(pattern="points_")
dat
ldf = lapply(dat, function(x) {
  # Add a column with the year
  dat$Year = substr(x,8,11)
  return(dat)
})
ldf
points_2014.shp$Year

但是最后一行还是返回NULL!

来自 this thread ,我调整了他们的解决方案。省略 do.call 和 rbind,这似乎可行:

lapply(points,
  function(x) {
    dat=get(x)
    dat$year = sub('.*_(.*)$','\\1',x)
    return(dat)
    })
points_2014.shp$year

但是最后一行返回一个空值。

开始怀疑我的 R 是否有问题。我使用 this example 对其进行了测试,并且有效,所以问题出在别处。

# a dataframe
a <- data.frame(x = 1:3, y = 4:6)
a
# make a list of several dataframes, then apply function 
#(change column names, e.g.):
my.list <- list(a, a)
my.list <- lapply(my.list, function(x) {
  names(x) <- c("a", "b") 
  return(x)})
my.list

在得到这个网站的一些帮助后,我的最终代码是:

#-------takes all the points files, adds the year, and then binds them together
points2<-do.call(rbind,lapply(ls(pattern='points_*'),
                              function(x) {
                                dat=get(x)
                                dat$year = substr(x,8,11)
                                dat
                              }))
points2$year
names(points2)

但是,它确实使用了 rbind,这在短期内很有帮助。从长远来看,我将需要再次拆分它,并使用 cbind,这样我就可以将两列相互减去。

最佳答案

我使用以下代码:

for (i in names.of.objects){
  temp <- get(i)
  # do transformations on temp
  assign(i, temp)
}

这可行,但绝对不是高性能的,因为它以按值调用的方式对整个数据进行两次赋值。

关于r - 使用 R 使用 lapply 将列添加到多个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41688755/

相关文章:

c++ - 为什么用作数组大小的函数的常量参数会出错?

c++ - 当对象绑定(bind)到成员函数时,为什么 std::function 会调用析构函数?

bash - 替换字符串中最后一次出现的子字符串 (bash)

Mysql子串

javascript - var 声明(例如 var x;)会覆盖以前的值

c - 如何在 C 中有效地从句子中提取单词?

r - 将交叉验证折叠分配给 for 循环中的数据集

r - data.table:当并非所有变量都在组内时,如何使用 %in% 过滤行?

r - R中非空数值向量的维数

r - 使用 Shiny 中的 slider 更改图像大小