简体   繁体   English

如何合并R中的多列

[英]How to combine multiple columns in R

Suppose I have this data set:假设我有这个数据集:

     age      height       weight
   "1/2/3"  "12/15/18"   "30/40/37"

How can I have a dataset like a dataset below?我怎样才能拥有像下面的数据集这样的数据集?

   age height weight
    1    12     30
    2    15     40
    3    18     37

And what if my dataset was like this:如果我的数据集是这样的怎么办:

  name     age      height       weight
 "Jack"  "1/2/3"  "12/15/18"   "30/40/37"

I want to have a data set like below:我想要一个如下的数据集:

    name  age height weight
   "Jack"  1    12     30
   "Jack"  2    15     40
   "Jack"  3    18     37

How can I do this?我怎样才能做到这一点?

If you don't mind using external package, you can use separate_rows() from the tidyr package.如果您不介意使用外部 package,您可以使用tidyr package 中的separate_rows()

library(tidyverse)

df %>% separate_rows(-name, sep = "/")

# A tibble: 3 × 4
  name  age   height weight
  <chr> <chr> <chr>  <chr> 
1 Jack  1     12     30    
2 Jack  2     15     40    
3 Jack  3     18     37    

If your data is in data frame format like this:如果您的数据是这样的数据帧格式:

df <- data.frame(age = '1/2/3', height = '12/15/18', weight = '30/40/37')

df
#>     age   height   weight
#> 1 1/2/3 12/15/18 30/40/37

You could do你可以做

as.data.frame(lapply(df, function(x) as.numeric(unlist(strsplit(x, '/')))))
#>   age height weight
#> 1   1     12     30
#> 2   2     15     40
#> 3   3     18     37

The same code will also work if your data is a named vector (it's not clear from the question what format your data is in, but the above code should work in either case as long as your data is called df )如果您的数据是命名向量,则相同的代码也将起作用(从问题中不清楚您的数据采用什么格式,但只要您的数据被称为df ,上述代码在任何一种情况下都应该起作用)

Created on 2022-04-10 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2022-04-10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM