簡體   English   中英

拆分數據幀行並重命名列

[英]Splitting Dataframe Rows And Renaming Columns

如果我有以下數據幀...

  X1      X2
1 a=12254 b=7052862
2 a=12130 b=7052862
3  a=7884 b=7052862
4   a=841 b=7052862
5  a=3486 b=7052862
6 a=11986 b=7052862

我怎樣才能將其轉換為以下內容。

a     b
1 12254 7052862
2 12130 7052862
3  7884 7052862
4   841 7052862
5  3486 7052862
6 11986 7052862

您可以使用tidyr提供的函數extract_numeric ,並將其應用於每個列:

library(tidyr)
names <- lapply(dat, function(x) strsplit(as.character(x[[1]]), "\\=")[[1]][1])
dat <- as.data.frame(apply(dat, 2, extract_numeric))
names(dat) <- unlist(names)
dat

      a       b
1 12254 7052862
2 12130 7052862
3  7884 7052862
4   841 7052862
5  3486 7052862
6 11986 7052862
library(dplyr)
library(tidyr)

test = 
  data_frame(
    X1 = c("a=12254" ,
           "a=12130",
           "a=7884",
           "a=841",
           "a=3486",
           "a=11986"),
    X2 = c(
      "b=7052862",
      "b=7052862",
      "b=7052862",
      "b=7052862",
      "b=7052862",
      "b=7052862"))

result = 
  test %>%
  mutate(ID = 1:n()) %>%
  gather(variable, value, -ID) %>%
  select(-variable) %>%
  separate(value, c("new_variable", "number"), sep = "=") %>%
  spread(new_variable, number)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM