[英]Is there a way to move every other row in a column into a new column in R?
挑战:我有一列有几行。 例如,第一行是“水果名称”,第二行是“水果颜色”,它对另一个水果重复。 我想抓住每隔一行(水果颜色)并创建一个新列。 在原始列中仅保留水果名称
library(tidyverse)
df_before <- tribble(~Singlecolumn,"Apple","Red","Banana","Yellow","Kiwi","Grey","Grapes","Green")
df_before
Singlecolumn
<chr>
Apple
Red
Banana
Yellow
Kiwi
Grey
Grapes
Green
#I would like to split this like below:
df_after <- tribble(~Column1, ~Column2, "Apple","Red","Banana","Yellow","Kiwi","Grey","Grapes","Green")
df_after
Column1 Column2
Apple Red
Banana Yellow
Kiwi Grey
Grapes Green
我确信有一种更简单的方法可以使用 tidyverse 中的函数来执行此操作,但无法通过大量搜索找到任何信息。 将不胜感激任何指针。 提前致谢!
更简单的选择是转换为具有 2 列的matrix
并转换为基础data.frame
中的base R
as.data.frame(matrix(df_before$Singlecolumn, ncol = 2, byrow = TRUE))
但是,我们也可以使用tidyverse
,我们使用rep
创建两个组,然后使用pivot_wider
将“long”格式重塑为“wide”格式
library(dplyr)
library(tidyr)
df_before %>%
group_by(grp = str_c('Column', rep(1:2, length.out = n()))) %>%
mutate(rn = row_number()) %>%
ungroup %>%
pivot_wider(names_from = grp, values_from = Singlecolumn) %>%
select(-rn)
# A tibble: 4 x 2
# Column1 Column2
# <chr> <chr>
#1 Apple Red
#2 Banana Yellow
#3 Kiwi Grey
#4 Grapes Green
您可以通过索引奇数和偶数列来做到这一点
# dummy data (please provide code to make a reproducible example in the future)
df1 <- data.frame(v1 = c("A", "a", "B", "b", "C", "c"))
# solution
df2 <- data.frame(
"col1" = df1[seq(1,length(df1[,1]),2), "v1"],
"col2" = df1[seq(2,length(df1[,1]),2), "v1"])
这里序列用于给出一个由 2 分隔的整数向量,使用seq()
function 从 1 或 2 运行到原始 dataframe 的长度,例如
seq(2,length(df1[,1]),2)
## [1] 2 4 6
然后将其传递给df[rows, columns]
方括号中的行。
我们可以使用逻辑值的向量循环来从df_before
获取备用数据。
data.frame(Column1 = df_before$Singlecolumn[c(TRUE, FALSE)],
Column2 = df_before$Singlecolumn[c(FALSE, TRUE)])
# Column1 Column2
#1 Apple Red
#2 Banana Yellow
#3 Kiwi Grey
#4 Grapes Green
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.