【发布时间】:2018-03-18 19:28:35
【问题描述】:
我想在时间 1、时间 2 和时间 3 计算变量“wt”和“wc”从时间 = 1 开始的百分比变化。在时间 1,它将为 0。在时间 2,它看起来像这样在 t2 = t2-t1/t1*100 和 t3 时,'wt' 的百分比变化应该看起来像 'wt' = t3-t1/t1*100。然后,我想将此作为新变量添加到现有的 excel 数据表中。我尝试寻找其他示例,但没有一个与我的数据格式匹配。谢谢!
structure(list(code = c(100, 100, 100, 101, 101, 101, 102, 102,
102), treatment = c(1, 1, 1, 2, 2, 2, 1, 1, 1), time = c(1, 2,
3, 1, 2, 3, 1, 2, 3), wt = c(80, 78, 76, 75, 74, 74, 78, 74,
72), wc = c(90, 89, 87, 92, 91, 90, 89, 86, 84)), .Names = c("code",
"treatment", "time", "wt", "wc"), row.names = c(NA, -9L),
class =c("tbl_df",
"tbl", "data.frame"))
我尝试遵循以下建议。但我收到一个错误
> data <- read.csv("All Data with BMI and other tweaks.csv", header = TRUE, na.strings = ".", stringsAsFactors = FALSE)
> names(data)
[1] "code" "treatment" "age" "sex"
[5] "time" "bicep" "tricep" "subscapular"
[9] "suprailiac" "weight" "pwc" "wc"
[13] "bia" "height" "bmi" "wthr"
[17] "density" "X.fat" "fm" "ffm"
[21] "dietary.recall" "reportingdate" "NumFoods" "NumCodes"
[25] "kcal" "prot" "tfat" "carb"
[29] "mois" "alc" "caff" "theo"
[33] "sugr" "fibe" "calc" "iron"
[37] "magn" "phos" "pota" "sodi"
[41] "zinc" "copp" "sele" "vc"
[45] "vb1" "vb2" "niac" "vb6"
[49] "fola" "fa" "ff" "fdfe"
[53] "vb12" "vara" "ret" "bcar"
[57] "acar" "cryp" "lyco" "lz"
[61] "atoc" "vk" "vitd" "choln"
[65] "chole" "sfat" "s040" "s060"
[69] "s080" "s100" "s120" "s140"
[73] "s160" "s180" "mfat" "m161"
[77] "m181" "m201" "m221" "pfat"
[81] "p182" "p183" "p184" "p204"
[85] "p205" "p225" "p226" "vite_add"
[89] "b12_add" "datacomp"
> library(dplyr)
> data <- data %>%
+ group_by(code) %>%
+ mutate(wt.pch = (data$weight - data$weight[1]) / data$weight * 100, wc.pch = (data$wc - data$wc[1]) / data$wc[1] * 100)
Error in mutate_impl(.data, dots) :
Column `wt.pch` must be length 3 (the group size) or one, not 114
【问题讨论】:
-
t2 - t1 / 100 * 100 是指 (t2 - t1 / 100) * 100?看起来很奇怪。我猜应该是 (t2 - t1) / t1 * 100。
-
@Julius 你是对的。我错了!
标签: r time-series