r - 按因子级别对数据进行分组,然后转换为以 colname 为级别的数据框?
问题描述
有我无法解决的问题:
数据:
df <- data.frame(f1=c("a", "a", "b", "b", "c", "c", "c"),
v1=c(10, 11, 4, 5, 0, 1, 2))
data.frame:f1 is factor
f1 v1
a 10
a 11
b 4
b 5
c 0
c 1
c 2
# What I want is:(for example, fetch data with the number of element of some level == 2, then to data.frame)
a b
10 4
11 5
提前致谢!
解决方案
我可能在这里遗漏了一些简单的东西,但下面使用的方法dplyr
有效。
library(dplyr)
nlevels = 2
df1 <- df %>%
add_count(f1) %>%
filter(n == nlevels) %>%
select(-n) %>%
mutate(rn = row_number()) %>%
spread(f1, v1) %>%
select(-rn)
这给
# a b
# <int> <int>
#1 10 NA
#2 11 NA
#3 NA 4
#4 NA 5
现在,如果你想删除NA
's 我们可以做
do.call("cbind.data.frame", lapply(df1, function(x) x[!is.na(x)]))
# a b
#1 10 4
#2 11 5
由于我们过滤了仅具有nlevels
观察值的数据框,因此最终数据框中的每一列将具有相同的行数。
推荐阅读
- powershell - pssession,调用命令没有得到变量
- actions-on-google - 保存用户信息 DialogFlow
- python - 调整大小和裁剪图像后查找新的 (X,Y)
- neural-network - Keras LSTM 让我的电脑崩溃了?
- typescript - 限制方法中的接口类型参数
- javafx - 有没有其他方法可以在 JavaFX 中解析和呈现 HTML 文本,而不是使用 WebView?
- python - 使用 Python 请求从西南请求数据时出现超时错误
- javascript - 表将无法使用 Firebase 生成
- php - 从 JSON 中提取数据并显示在 SWAL 警报中
- sockets - Raw socket UDP programming