如何在R中按列名称拆分数据帧? [英] How to split data frame by column names in R?

查看:89
本文介绍了如何在R中按列名称拆分数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在24小时内一直在寻找自己觉得很琐碎的问题(对我来说不是R的新手),但尚未结出硕果.所以请帮帮我.我有一个数据框,希望将其拆分为两个.这是数据的样子;

My 24 hours of search for what I feel is a trivial (Not for a newbie in R as I am) problem has not yet born fruits. So please help me out. I have a single data frame that I would wish to split into two. Here is how the data looks like;

d1 d2 d3 d4 p1 p2 p3 p4
30 40 20 60 1  3  2  5  
20 50 40 30 3  4  1  5 
40 20 50 30 2  3  1  4 

这是我想要的样子;

$d
d1 d2 d3 d4
30 40 20 60
20 50 40 30
40 20 50 30 

$p
p1 p2 p3 p4
1  3  2  5 
3  4  1  5
2  3  1  4

我已经尝试过在线使用大多数命令和示例,但是它们似乎都在沿行拆分数据,例如:

I have tried to most of the commands and examples online but they all seem to be splitting data along rows such as in:

split(1:3, 1:2)

即使使用索引,我如何仍要从前四列中拆分出前四列呢?

How can I indicate even with the use of indexes that I want to split the first 4 columns from the last four?

推荐答案

使用sapplystartsWith:

sapply(c("d", "p"),
       function(x) df[startsWith(names(df),x)],
       simplify = FALSE)

# $d
# d1 d2 d3 d4
# 1 30 40 20 60
# 2 20 50 40 30
# 3 40 20 50 30
# 
# $p
# p1 p2 p3 p4
# 1  1  3  2  5
# 2  3  4  1  5
# 3  2  3  1  4

tidyverse的翻译:

library(tidyverse)
map(set_names(c("d", "p")),~select(df,starts_with(.x)))
# $d
# d1 d2 d3 d4
# 1 30 40 20 60
# 2 20 50 40 30
# 3 40 20 50 30
# 
# $p
# p1 p2 p3 p4
# 1  1  3  2  5
# 2  3  4  1  5
# 3  2  3  1  4

这篇关于如何在R中按列名称拆分数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆