我有几个具有相同列结构但具有不同行结构的文件 (20)。全部由两列组成,第一列是因子,第二列是整数。我想对重复因子和简单添加的新因子的整数列进行求和。我怎样才能将已经重复的内容合并起来并求和?
我考虑过将 cbind 和 tapply 结合起来,但我真的不知道如何实现。
文件结构的简单示例:
Shop Clients Shop Clients Shop Clients
A 9 D 8 A 5
B 7 A 4 R 4
C 4 F 3 C 3
D 2 B 1 B 2
我期望的输出:
Shop Clients
A 18
B 10
C 7
D 10
F 3
R 4
我循环读取不同的文件,为每个文件创建一个数据集,以便数据集显示 City1$Shop 和 City1$Clients。此案例仅适用于 20 个文件,但我想知道如何处理更多文件(例如 100 个)。 我如何通过这种方式读取数据集来解决这个问题?
f<-function(x){
read.delim2("p01.txt",header=T,sep="\t",stringsAsFactors = FALSE)
}
for(i in x){
total<-f(i)
#Here I suppose I would combine and sum the datasets
}
最佳答案
一种可能性是在将数据 reshape 为长格式后使用aggregate
。
inx <- grep("Shop", names(df1))
long <- do.call(rbind, lapply(inx, function(i) df1[i:(i + 1)]))
aggregate(Clients ~ Shop, long, sum)
# Shop Clients
#1 A 18
#2 B 10
#3 C 7
#4 D 10
#5 F 3
#6 R 4
编辑。
编辑问题后,我相信以下内容符合要求。我将再次使用aggregate
。
fnames <- list.files(pattern = "\\.txt")
df_list <- lapply(fnames, read.table, header = TRUE)
df_all <- do.call(rbind, df_list)
aggregate(Clients ~ Shop, data = df_all, sum)
关于r - 如何对不具有相同结构的多个数据集的列求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56225142/