我有几个 csv 文件,全部以日期命名,对于所有文件,我想在每个文件中创建一个新列,其中包含来自其他两列放在一起的数据。然后,我想将它们组合成一个大数据框,并仅选择其中两列来保留。这是一个例子:
假设我有两个数据框:
a b c a b c
x 1 2 3 x 3 2 1
y 2 3 1 y 2 1 3
然后我想在每个列中创建一个新的 d 列:
a b c d a b c d
x 1 2 3 13 x 3 2 1 31
y 2 3 1 21 y 2 1 3 23
然后我想像这样组合它们:
a b c d
x 1 2 3 13
y 2 3 1 21
x 3 2 1 31
y 2 1 3 23
然后保留两列a和d并删除另外两列b和c:
a d
x 1 13
y 2 21
x 3 31
y 2 23
这是我当前的代码(当我尝试合并其中两列或尝试仅保留其中两列时,它不起作用):
f <- list.files(pattern="201\\d{5}\\.csv") # reading in all the files
mydata <- sapply(f, read.csv, simplify=FALSE) # assigning them to a dataframe
do.call(rbind,mydata) # combining all of those dataframes into one
mydata$Data <- paste(mydata$LAST_UPDATE_DT,mydata$px_last) # combining two of the columns into a new column named "Data"
c('X','Data') %in% names(mydata) # keeping two of the columns while deleting the rest
物体mydata
是数据框的列表。您可以使用以下命令更改列表中的数据框lapply
:
lapply(mydata, function(x) "[<-"(x, "c", value = paste0(x$a, x$b)))
file1 <- "a b
x 2 3"
file2 <- "a b
x 3 1"
mydata <- lapply(c(file1, file2), function(x) read.table(text = x, header =TRUE))
lapply(mydata, function(x) "[<-"(x, "c", value = paste0(x$a, x$b)))
# [[1]]
# a b c
# x 2 3 23
#
# [[2]]
# a b c
# x 3 1 31
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)