英文:
Pivot- turning rows to columns but keeping listing values underneath each column
问题
我是新手学习R编程,我试图将我的网站作为列,将数字列为值,并在下面单独的行中列出。这是我的数据以及我尝试做的事情。
matrix <- as.data.frame(matrix(c(1982,1923,3445,2345,12345,1234,"Site1","Site2","Site2","Site1","Site2","Site3"), nrow=6,ncol=2))
matrix <- matrix %>%
pivot_wider(names_from= V2, values_from = V1)
我尝试获得以下结果:
Site1 | Site2 | Site3 |
---|---|---|
1982 | 1923 | 1234 |
2345 | 3445 | |
12345 |
我需要进行pivot_longer吗?
英文:
I am new to R programming, and I am trying to get my Sites as columns and my numbers listed as values in separate rows underneath. Here's my data and what I've tried to do.
matrix <- as.data.frame(matrix(c(1982,1923,3445,2345,12345,1234,"Site1","Site2","Site2","Site1","Site2","Site3"), nrow=6,ncol=2))
matrix <- matrix %>%
pivot_wider(names_from= V2, values_from = V1)
I'm trying to get the following:
Site1 | Site2 | Site3 |
---|---|---|
1982 | 1923 | 1234 |
2345 | 3445 | |
12345 |
Do I need to pivot_longer?
答案1
得分: 0
这肯定还是一个 pivot_wider
操作 - 你只需生成一个用于指定唯一行以进行透视的 id 列:
library(tidyr)
library(dplyr)
matrix %>%
group_by(V2) %>%
mutate(id = row_number()) %>%
pivot_wider(id_cols = id, names_from = V2, values_from = V1)
## id Site1 Site2 Site3
## <int> <chr> <chr> <chr>
##1 1 1982 1923 1234
##2 2 2345 3445 NA
##3 3 NA 12345 NA
英文:
It's definitely still a pivot_wider
- you just need to generate an id column to be used for specifying the unique rows to pivot against:
library(tidyr)
library(dplyr)
matrix %>%
group_by(V2) %>%
mutate(id = row_number()) %>%
pivot_wider(id_cols = id, names_from= V2, values_from = V1)
## id Site1 Site2 Site3
## <int> <chr> <chr> <chr>
##1 1 1982 1923 1234
##2 2 2345 3445 NA
##3 3 NA 12345 NA
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论