将行转为列,但保持每列下面的列出的值。

huangapple go评论126阅读模式
英文:

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 %&gt;%
    group_by(V2) %&gt;%
    mutate(id = row_number()) %&gt;%
    pivot_wider(id_cols = id, names_from= V2, values_from = V1)
##     id Site1 Site2 Site3
##  &lt;int&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
##1     1 1982  1923  1234 
##2     2 2345  3445  NA   
##3     3 NA    12345 NA 

huangapple
  • 本文由 发表于 2023年6月16日 05:21:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定