[英]How do I create two new variables out of one variable, and attach dummy values to it in R?
[英]How do I create variables in R that count the number of values of one variable by another variable?
这是我的数据:
Name Grade
1 John Smith C
2 John Smith B
3 John Smith C
4 Jane Doe A
5 Jane Doe C
6 Lisa Brown B
我试图得到这个:
Name A B C
1 John Smith 0 1 2
4 Jane Doe 1 0 1
6 Lisa Brown 0 1 0
我知道我可以通过使用 table 或 with function 将它作为控制台中的 table 获取,但它不会以这种方式存储为数据帧。 有任何想法吗?
这里有两个解决方案:
使用tabyl()
从janitor
包:
library(janitor) tabyl(df, name, grade) name ABC Jane Doe 1 0 1 John Smith 0 1 2 Lisa Brown 0 1 0
使用pivot_wider()
从tidyr
:
* 注意:更新了 Darren Tsai 的回答中更好的语法。
library(tidyr) df %>% pivot_wider(id_cols = name, names_from = grade, names_sort = TRUE, values_from = grade, values_fn = length, values_fill = 0) # A tibble: 3 x 4 name ABC <chr> <dbl> <dbl> <dbl> 1 John Smith 0 1 2 2 Jane Doe 1 0 1 3 Lisa Brown 0 1 0
带有table()
和as.data.frame.matrix()
的base
解决方案,它返回一个带有行名称的data.frame
对象。 您可以轻松地将行名称调整为新列。
as.data.frame.matrix(table(df))
# A B C
# Jane Doe 1 0 1
# John Smith 0 1 2
# Lisa Brown 0 1 0
您还可以通过实现它pivot_wider()
从tidyr
只有一个电话。
library(tidyr)
pivot_wider(df, names_from = Grade,
names_sort = TRUE,
values_from = Grade,
values_fill = 0,
values_fn = length)
# # A tibble: 3 x 4
# Name A B C
# <chr> <int> <int> <int>
# 1 John Smith 0 1 2
# 2 Jane Doe 1 0 1
# 3 Lisa Brown 0 1 0
数据
df <- structure(list(Name = c("John Smith", "John Smith", "John Smith",
"Jane Doe", "Jane Doe", "Lisa Brown"), Grade = c("C", "B", "C",
"A", "C", "B")), class = "data.frame", row.names = c(NA, -6L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.