簡體   English   中英

如何將特定行轉換為R中的列?

[英]How to convert specific rows into columns in r?

我在R中的df僅來自亞馬遜的一列食品等級。

head(food_ratings)
          product.productId..B001E4KFG0
1         review/userId: A3SGXH7AUHU8GW
2        review/profileName: delmartian
3               review/helpfulness: 1/1
4                     review/score: 5.0
5               review/time: 1303862400
6 review/summary: Good Quality Dog Food

這些行會重復,因此行7到12具有關於另一個用戶的相同信息(行7)。 此模式重復了很多次。

因此,我需要將每6行中的每組分配為6列的一行,以便以后我可以根據其評論/分數將其作為子集。

我正在使用RStudio 1.0.143

編輯:我被要求顯示dput(head(food_ratings, 24))的輸出,但是無論使用多少,它都太大了。 非常感謝

我已收集了您的數據,並添加了2個其他虛假用戶。 使用tidyrdplyr可以創建新列,並將數據折疊到一個不錯的data.frame中。 如果不需要,可以使用dplyr select刪除id列或重新排列列的順序。

library(tidyr)
library(dplyr)

df %>% 
  separate(product.productId..B001E4KFG0, into = c("details", "data"), sep = ": ") %>% 
  mutate(details = sub("review/ ", "", details)) %>% 
  group_by(details) %>% 
  mutate(id = row_number()) %>% 
  spread(details, data)


# A tibble: 3 x 7
     id helpfulness profileName score summary                 time       userId        
  <int> <chr>       <chr>       <chr> <chr>                   <chr>      <chr>         
1     1 1/1         delmartian  5.0   Good Quality Dog Food   1303862400 A3SGXH7AUHU8GW
2     2 1/1         martian2    1.0   Good Quality Snake Food 1303862400 123456        
3     3 2/5         martian3    5.0   Good Quality Cat Food   1303862400 123654  

數據:

df <- structure(list(product.productId..B001E4KFG0 = c("review/userId: A3SGXH7AUHU8GW", 
"review/profileName: delmartian", "review/helpfulness: 1/1", 
"review/score: 5.0", "review/time: 1303862400", "review/summary: Good Quality Dog Food", 
"review/userId: 123456", "review/profileName: martian2", "review/helpfulness: 1/1", 
"review/score: 1.0", "review/time: 1303862400", "review/summary: Good Quality Snake Food", 
"review/userId: 123654", "review/profileName: martian3", "review/helpfulness: 2/5", 
"review/score: 5.0", "review/time: 1303862400", "review/summary: Good Quality Cat Food"
)), class = "data.frame", row.names = c(NA, -18L))

暫無
暫無

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

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