[英]How to condense a data frame into two columns based of a specific column entry
如果我有如下數據集
Rater1 10 a
Rater2 12 b
Rater2 5 c
Rater1 7 d
我應該如何編碼 R 以將數據轉換為兩列中的格式
Rater1 Rater2
10 12
7 5
a b
d c
對那個
您可以執行以下操作:
as.data.frame(lapply(split(df, df$Rater), \(d) c(d$v1,d$v2)))
Output:
Rater1 Rater2
1 10 12
2 7 5
3 a b
4 d c
輸入:
df = structure(list(Rater = c("Rater1", "Rater2", "Rater2", "Rater1"
), v1 = c(10, 12, 5, 7), v2 = c("a", "b", "c", "d")), class = "data.frame", row.names = c(NA,
-4L))
請注意,您的最終 dataframe 具有包含數字和字符的列,並且由於一列只能包含一個 class 所有數字都會變成字符。
我們可以在dplyr
和tidyr
庫的幫助下做到這一點。 首先我們將列更改為字符,獲取長格式數據,創建行號列來唯一標識每一行,最后獲取寬格式數據。
library(dplyr)
library(tidyr)
df %>%
mutate(across(.fns = as.character)) %>%
pivot_longer(cols = -Rater) %>%
group_by(Rater) %>%
mutate(name = row_number()) %>%
ungroup %>%
pivot_wider(names_from = Rater, values_from = value) %>%
select(-name)
# Rater1 Rater2
# <chr> <chr>
#1 10 12
#2 a b
#3 7 5
#4 d c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.