[英]How do I convert a data frame with multiple variables in rows from wide to long in R?
I have a data frame that looks like:我有一个看起来像的数据框:
Amount person1 person2 person3
pocketmoney 0.5 1.3 1.7
chores 3 5 2
How do I turn it into something like this:我如何把它变成这样的东西:
Person Pocketmoney chores
person1 0.5 3
person2 1.3 5
person3 1.7 2
Thanks!谢谢!
We may use data.table::transpose
我们可以使用
data.table::transpose
library(data.table)
data.table::transpose(setDT(df1), make.names = "Amount",
keep.names = 'Person')[]
-output -输出
Person pocketmoney chores
<char> <num> <num>
1: person1 0.5 3
2: person2 1.3 5
3: person3 1.7 2
Or using base R
或者使用
base R
data.frame(Person = seq_along(df1[-1]), t(df1[-1]))
df1 <- structure(list(Amount = c("pocketmoney", "chores"), person1 = c(0.5,
3), person2 = c(1.3, 5), person3 = c(1.7, 2)),
class = "data.frame", row.names = c(NA,
-2L))
Using tidyr:使用整理器:
> df1 %>%
pivot_longer(-Amount) %>%
pivot_wider(names_from = Amount, values_from = value) %>%
mutate(name = sub("\\D+", "", name)) # remove "person"
# A tibble: 3 × 3
name pocketmoney chores
<chr> <dbl> <dbl>
1 1 0.5 3
2 2 1.3 5
3 3 1.7 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.