簡體   English   中英

需要從不同行收集值並組合成一行

[英]Need to collect values from different rows and combine into one row

我是 R 的新手,到目前為止我一直做得很好,但我現在需要做一些復雜的事情,並且不能讓它工作。 我有一個類似於以下的數據集(以后我將稱之為 df):

df <- tribble(~name,             ~word,             ~N,
              "brandon",         "hello",            3,
               "john",           "test",             5,
               "jim",            "hello",            2,
               "brandon",        "goodbye",          2,
               "brandon",        "test",             1,
               "jim",            "goodbye",          4)

到目前為止,我有這樣的事情發生:

temp_df <- df %>% mutate(
                     "hello" = ifelse(word == "hello", N, 0),
                     "goodbye" = ifelse(word == "goodbye", N, 0),
                     "test" = ifelse(word == "test", N, 0)
                  )

它正在創造這樣的東西:

name            hello           goodbye        test        word         N
brandon         3               0              0           hello        3
john            0               0              5           test         5
jim             2               0              0           hello        2
brandon         0               2              0           goodbye      2
brandon         0               0              1           test         1
jim             0               4              0           goodbye      4

但我需要 df 看起來像這樣:

name            hello           goodbye        test
brandon         3               2              1
john            0               0              5
jim             2               4              0

在這里完成后,我知道如何選擇()重要數據,但我只是不確定如何將每個名稱的所有數據放入一行。 請停下來:)

PS如果有人在這里有一個更好的標題的建議,將不勝感激

使用dplyr

df %>%
  pivot_wider(id_cols="name", names_from="word", values_from="N", values_fill=0)

產量

# A tibble: 3 x 4
  name    hello  test goodbye
  <chr>   <dbl> <dbl>   <dbl>
1 brandon     3     1       2
2 john        0     5       0
3 jim         2     0       4

數據框

df <- tribble(~name,             ~word,             ~N,
              "brandon",         "hello",            3,
               "john",           "test",             5,
               "jim",            "hello",            2,
               "brandon",        "goodbye",          2,
               "brandon",        "test",             1,
               "jim",            "goodbye",          4)

解決方案

library(dplyr) 
  df %>%
  pivot_wider(id_cols="name", names_from="word", values_from="N", 
  values_fill=0)

pivot_wider() “加寬”數據,增加列數並減少行數。 逆變換是pivot_longer()

help() function 和? R 中的幫助操作員提供對 R 函數、數據集和其他對象的文檔頁面的訪問,包括標准 R 分發包和貢獻包中的包。 例如, help(pivot_wider)?pivot_wider

Output

    name    hello   test    goodbye
    brandon 3       1       2   
    john    0       5       0   
    jim     2       0       4   

暫無
暫無

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

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