有没有办法将列中的每隔一行移动到 R 中的新列中? [英] Is there a way to move every other row in a column into a new column in R?
问题描述
挑战:我有一列有几行.例如,第一行是水果名称",第二行是水果颜色",对于另一个水果重复.我想抓取每隔一行(水果颜色)并创建一个新列.在原始列中只保留水果名称
Challenge: I have a column in which there are several rows. For eg., the first row is "Fruit name" and second row is "Fruit Color" and it repeats for another fruit. I want to grab the every second row (Fruit color) and create a new column. In the original column only the fruit names remain
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 中的函数有一种更简单的方法可以做到这一点,但通过大量搜索找不到任何信息.将不胜感激任何指针.提前致谢!
I'm sure there is a easier way to do this using functions from tidyverse but couldn't find any info with a good deal of search. Would appreciate any pointers. Thanks in advance!
推荐答案
我们可以使用逻辑值的向量回收来从 df_before
中获取替代数据.
We can use vector recycling of logical values to get alternate data from 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
这篇关于有没有办法将列中的每隔一行移动到 R 中的新列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!