簡體   English   中英

如何使用R將包含一列相同值但其他列不同的行轉換為一行?

[英]How to convert rows that contain same value for one column but different for other columns into one single row using R?

我有以下數據:

User_Id      Website      Day
A        Google    Monday
A        Facebook   Tuesday
A        Linkedin    Wednesday
B        Facebook   Tuesday
B       Linkedin    Wednesday

我想實現以下目標:

User_ID   Google  Facebook  Linkedin  Monday  Tuesday  Wednesday
A        1       1         1          1       1        1
B        0       1         1          0       1        1

現在,這些列代表每個用戶出現的次數。 我如何在R中做到這一點?

我們unlist的第二和的第三列data.frameunlist(df1[-1]和復制由其他列的數量的第一列,即在這種情況下圖2( rep(df1[,1], 2)得到使用table進行頻率計數並轉換為data.frameas.data.frame.matrix )。

as.data.frame.matrix(table(rep(df1[,1],2), unlist(df1[-1])))
#  Facebook Google Linkedin Monday Tuesday Wednesday
#A        1      1        1      1       1         1
#B        1      0        1      0       1         1

如果需要打包解決方案,則另一個選擇是dplyr/tidyr 通過gather (來自tidyr )將“寬”格式重塑為“長”格式,獲取頻率countspread回“寬”格式。

library(dplyr)
library(tidyr)
df1 %>%
    gather(Var, Val, -User_Id) %>%
    count(User_Id, Val) %>% 
    spread(Val, n, fill = 0)   
#   User_Id Facebook Google Linkedin Monday Tuesday Wednesday
#    <chr>    <dbl>  <dbl>    <dbl>  <dbl>   <dbl>     <dbl>
#1       A        1      1        1      1       1         1
#2       B        1      0        1      0       1         1

一個帶有reshape2::recast的選項,它基本上首先通過User_Id將所有列轉換為長格式,然后再次根據User_Id散布回去

library(reshape2)
recast(df, User_Id ~ value, id.var = "User_Id", length)
#   User_Id Facebook Google Linkedin Monday Tuesday Wednesday
# 1       A        1      1        1      1       1         1
# 2       B        1      0        1      0       1         1

暫無
暫無

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

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