R 从另一个数据框中的唯一值和分配给列的相应值创建具有列名的新数据框
我是R新手,我很确定这是一件很容易完成的事情,但我不知道如何执行这个操作。我尝试过使用for循环的split函数,但不太清楚如何正确使用它。例如,我的原始数据帧就是这样的:R 从另一个数据框中的唯一值和分配给列的相应值创建具有列名的新数据框,r,reshape,R,Reshape,我是R新手,我很确定这是一件很容易完成的事情,但我不知道如何执行这个操作。我尝试过使用for循环的split函数,但不太清楚如何正确使用它。例如,我的原始数据帧就是这样的: dat <- data.frame(col1 = c(rep("red", 4), rep("blue", 3)), col2 = c(1, 3, 2, 4, 7, 8, 9)) col1 col2 red 1 red 3 red 2 red 4 blue 7 bl
dat <- data.frame(col1 = c(rep("red", 4), rep("blue", 3)), col2 = c(1, 3, 2, 4, 7, 8, 9))
col1 col2
red 1
red 3
red 2
red 4
blue 7
blue 8
blue 9
我已经接近我想要的列表结构,但是我需要一个数据框来框绘和点绘结果。任何帮助都将受到感谢。谢谢 我肯定有更有效的解决方案,但这里有一个选择
dat <- data.frame(col1 = c(rep("red", 4), rep("blue", 3)), col2 = c(1, 3, 2, 4, 7, 8, 9))
dat
col1 col2
1 red 1
2 red 3
3 red 2
4 red 4
5 blue 7
6 blue 8
7 blue 9
ust <- unstack(dat, form = col2 ~ col1)
res <- data.frame(sapply(ust, '[', 1:max(unlist(lapply(ust, length)))))
res
blue red
1 7 1
2 8 3
3 9 2
4 NA 4
这里有一个可能的解决方案
library(tidyr)
library(dplyr)
dat %>%
group_by(col1) %>%
mutate(n = row_number()) %>%
spread(col1, col2)
# Source: local data frame [4 x 3]
#
# n blue red
# 1 1 7 1
# 2 2 8 3
# 3 3 9 2
# 4 4 NA 4
或使用data.table
library(data.table)
dcast(setDT(dat)[, indx := 1:.N, by = col1], indx ~ col1, value.var = "col2")
# indx blue red
# 1: 1 7 1
# 2: 2 8 3
# 3: 3 9 2
# 4: 4 NA 4
只需使用base R
*apply
和cbind
# split the data into list using col1 column
tmp.list = lapply(split(dat, dat$col1), function(x) x$col2)
# identify the length of the biggest list
max.length = max(sapply(tmp.list, length))
# combine the list elements, while filling NA for the missing values
data.frame(do.call(cbind,
lapply(tmp.list, function(x) c(x, rep(NA, max.length - length(x))))
))
# blue red
#1 7 1
#2 8 3
#3 9 2
#4 NA 4
hmmm
unstack
,从未听说过这一次我正在使用它来绘制我医院每个诊所的门诊预约等待时间,它已经为我们提供了一个以前在确定特定问题诊所时从未有过的视图。我们的患者也会心存感激!!好消息!由于此解决方案适用于您,您可以单击问题旁边的复选标记以接受。这给我和你(我想):)我说的对吗,你总是需要一个“行标识符列”(这里:n)来让它与dplyr一起工作?我不确定你总是需要什么,这只是我提出的解决方案。因此“可能”在顶部。当然。我想我不会经常尝试转换我以前没有融化过的数据。是的,我想这些数据会错过“变量”列。@maj有一个功能请求需要忽略它:
library(data.table)
dcast(setDT(dat)[, indx := 1:.N, by = col1], indx ~ col1, value.var = "col2")
# indx blue red
# 1: 1 7 1
# 2: 2 8 3
# 3: 3 9 2
# 4: 4 NA 4
# split the data into list using col1 column
tmp.list = lapply(split(dat, dat$col1), function(x) x$col2)
# identify the length of the biggest list
max.length = max(sapply(tmp.list, length))
# combine the list elements, while filling NA for the missing values
data.frame(do.call(cbind,
lapply(tmp.list, function(x) c(x, rep(NA, max.length - length(x))))
))
# blue red
#1 7 1
#2 8 3
#3 9 2
#4 NA 4