如何在R中组合多列

发布于 2025-01-20 09:18:39 字数 541 浏览 2 评论 0原文

假设我有这个数据集:

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

我怎样才能拥有像下面的数据集这样的数据集?

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

如果我的数据集是这样的怎么办:

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

我想要一个如下所示的数据集:

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

我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初见 2025-01-27 09:18:39

如果您不介意使用外部软件包,则可以从TIDYR软件包中使用axtim_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 you don't mind using external package, you can use separate_rows() from the tidyr package.

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    
小情绪 2025-01-27 09:18:39

如果您的数据采用这样的数据帧格式:

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

您可以这样做

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

如果您的数据是命名向量,则相同的代码也将起作用(从问题中不清楚您的数据采用什么格式,但上面的代码在任何情况下都应该起作用只要您的数据名为 df)

reprex 包 (v2.0.1)

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)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文