我有一个包含50种不同动物(猫和狗的例子在下面)和8个观察值(下面给出三个例子)的数据框架,我想计算每种动物在每一天( _1,_2,_3)和第0天(_0)以及前一天(例如,cats_3- cats _2)之间的差异。
df <- read.table(text =
'shelter cats_0 cats_1 cats_2 cats_3 dogs_0 dogs_1 dogs_2 dogs_3
blue 4 4 2 1 3 4 8 3
yellow 3 6 5 3 2 5 6 3
green 2 7 3 2 8 4 2 2
red 5 6 6 4 4 5 9 6
orange 6 4 1 1 6 3 2 1'
header = TRUE )
下面的“答案”只适用于猫。我确实意识到这将是一张非常宽的桌子!
df <- read.table(text =
"shelter cats_0 cats_1 cats_2 cats_3 cats_1-0 cats_2-0 cats_3-0 cats_2-1 cats_3-2
blue 4 4 2 1 0 -2 -3 -2 -1
yellow 3 6 5 3 3 2 0 -1 -2
green 2 7 3 2 5 1 0 -4 -1
red 5 6 6 4 1 1 -1 0 -2
orange 6 4 1 1 -2 -5 -5 -3 0",
header = TRUE
)
有没有简单的方法可以做到这一点?我尝试使用grep和一个带有动物名称的对象,但无法使其正常工作。
发布于 2016-12-13 05:27:04
不是最漂亮的代码,但没有依赖关系,如果每个代码都小于10就可以了:
new_cats <- df[,grep("cats_[1-9]$", colnames(df), value=TRUE)] - df[,"cats_0"]
new_dogs <- df[,grep("dogs_[1-9]$", colnames(df), value=TRUE)] - df[,"dogs_0"]
df <- cbind.data.frame(df, setNames(new_cats, sprintf("%s_0", colnames(new_cats))))
df <- cbind(df, setNames(new_dogs, sprintf("%s_0", colnames(new_dogs))))
https://stackoverflow.com/questions/41109495
复制相似问题