簡體   English   中英

擴展到R中的一列

[英]Spreading over a column in R

所以說我有一個這樣的數據框:

data.frame(x = c(1,1,1,3,3,3),y = c(12,32,43,16,32,65))

我想將其轉換為這樣的數據幀:

data.frame(x = c(1, 3), y_1 =  c(12,16), y_2 =c(32, 32),y_3= c(43, 65))

基本上將每個唯一x值的y值散布。 我嘗試使用tidyr進行此操作,但還不太清楚它是如何工作的。 有任何想法嗎?

謝謝。

這是一個data.table解決方案:

library(data.table)

dat = as.data.table(df) # or setDT to convert in place

dat[, obs := paste0('y_', 1:.N), by=x]
dcast(dat, x ~ obs, value.var="y")

#   x y_1 y_2 y_3
#1: 1  12  32  43
#2: 3  16  32  65

即使所有x的行數都不相同,這也將起作用。

我們可以用aggregate ,然后cSplitsplitstackshape包強迫到數據幀時,

library(splitstackshape)
df1 <- aggregate(y ~ x, df, paste, collapse = ',')
df1 <- cSplit(df1, 'y', ',', direction = 'wide')
#   x y_1 y_2 y_3
#1: 1  12  32  43
#2: 3  16  32  65

Sotos使用aggregate給出的答案特別優雅,但是以下使用reshape方法也可能具有指導意義:

df <- data.frame(x = c(1,1,1,3,3,3),y = c(12,32,43,16,32,65))
df[,"time"] <- rep(1:3, 2)
wide_df <- reshape(df, direction="wide", timevar="time", idvar="x")

dplyr/tidyr一種選擇

library(dplyr)
library(tidyr)
df1 %>% 
    group_by(x) %>% 
    mutate(n = paste("y", row_number(), sep="_")) %>%
    spread(n,y)
#     x   y_1   y_2   y_3
#   (dbl) (dbl) (dbl) (dbl)
#1     1    12    32    43
#2     3    16    32    65

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM