因此,给定以下列,我需要创建一个包含列之间的差异的新数组。例如,在下面的示例中,我需要创建一个数组,该数组包含每所房子按str计算的平均一分和两分之间的差值,到目前为止,我有一些类似汇总的东西(diff=abs(diff(1,2)),.groups = "drop"),但这并不是很好的解决方法,我可以这样做吗?
,,house = reg
str one two three
reg 443 518 440
smol 342 587 432
regai 534 597 443
,,house = smol
str one two three
reg 530 586 435
smol 541 597 447
regai 539 602 439所以我的理想输出看起来像这样,而不是数据帧,一个数组看起来像这样:
str reg smol
reg 440-518 435-586
smol 432-587 447-597
regai 443-597 439-602所以我要做的是提取每一列,创建新的列,然后在最后合并所有的差异,但这个过程会花费太长的时间,所以我试图找到更短的方法。此外,我还需要确保输出是绝对值
update now我正在做这样的事情:
diff =(abs(df$3-df$2))
发布于 2020-12-10 04:17:55
我们可以做到
cbind(df1[1], setNames(lapply(list(df1, df2),
function(x) abs(x$three - x$two)), c('reg', 'smol')))-output
# str reg smol
#1 reg 78 151
#2 smol 155 150
#3 regai 154 163如果它是从xtabs创建的array,则选项也是
out1 <- lapply(seq_len(dim(input_data)[3]), function(i) {
x <- as.data.frame(input_data[,, i])
abs(x$three - x$two)
})
names(out1) <- c('reg', 'smol')
cbind(as.data.frame(input_data[,,1])[1]), out1)数据
df1 <- structure(list(str = c("reg", "smol", "regai"), one = c(443L,
342L, 534L), two = c(518L, 587L, 597L), three = c(440L, 432L,
443L)), class = "data.frame", row.names = c(NA, -3L))
df2 <- structure(list(str = c("reg", "smol", "regai"), one = c(530L,
541L, 539L), two = c(586L, 597L, 602L), three = c(435L, 447L,
439L)), class = "data.frame", row.names = c(NA, -3L))https://stackoverflow.com/questions/65224020
复制相似问题