将列拆分为行,并为R中的新行更改特定列值

时间:2018-05-02 13:50:36

标签: r

我有一个包含多列的数据框如下:

 Frequency                 Alels
   0.5                      C
   0.6                      C,G
   0.02                     A,T,TTT

我想分割第二列的值,新行有frequency = 0

我尝试使用tidyr包中的separate(),但我无法更改新行中的frequency列,我得到了上述结果:

Frequency                 Alels
   0.5                      C
   0.6                      C
   0.6                      G
   0.02                     A
   0.02                     T
   0.02                    TTT

但我希望输出如下:

Frequency                 Alels
   0.5                      C
   0.6                      C
   0                        G
   0.02                     A
   0                        T
   0                        TTT

我尝试使用tidyr包中的separate(),但我无法更改新行中的frequency列。

3 个答案:

答案 0 :(得分:0)

这应该有效:

d <- read.table(text = "Frecuency                 Alels
   0.5                      C
                0.6                      C,G",
                header = T, stringsAsFactors = F)

counts <- sapply(strsplit(d$Alels, split = ","), length)

data.frame("Frecuency" = unlist(lapply(seq_along(d$Frecuency),
                                       function(x) c(d$Frecuency[x], 
                                                     rep(0, counts[x] -1)))), 
           "Alels" = unlist(strsplit(d$Alels, split = ",")))

答案 1 :(得分:0)

不漂亮,但我认为它有效。

# Create data frame 
df <- data.frame(frequency = c(0.5, 0.6),
                 alels = c("C", "C, G, T"),
                 stringsAsFactors = FALSE)

# Duplicate the alels column, separate rows 
# Requires magrittr, dplyr, tidyr
df %<>% 
  mutate(alels_check = alels) %>% 
  separate_rows(alels, sep = ",", convert = TRUE)  

# Check for dupes and set them to zero
df[duplicated(df$frequency, df$alels_check),]$frequency <- 0

# Remove the duplicated alels column
df %<>% select(-alels_check)

原件:

#    frequency   alels
# 1       0.5       C
# 2       0.6 C, G, T

结果:

#    frequency alels
# 1       0.5     C
# 2       0.6     C
# 3       0.0     G
# 4       0.0     T

使用您的数据:

#   frequency     alels
# 1      0.50         C
# 2      0.60      C, G
# 3      0.02 A, T, TTT

#   frequency alels
# 1      0.50     C
# 2      0.60     C
# 3      0.00     G
# 4      0.02     A
# 5      0.00     T
# 6      0.00   TTT 

答案 2 :(得分:0)

您示例中的数据:

df <- read.table(text = " Frequency                 Alels
   0.5                      C
             0.6                      C,G
             0.02                     A,T,TTT",
            header = T, stringsAsFactors = F)

和另一个解决方案供您考虑:

library(dplyr)

lapply(1:nrow(df), 
   function(row_num){
     s <- strsplit(df$Alels[row_num], ",") %>% unlist
     data.frame(Frequency = c(df$Frequency[row_num], rep(0,length(s)-1)),
                Alels = s)
     }) %>% do.call(rbind, .)
df

而不是do.call(rbind, .)您还可以选择使用包rbindlist()

中的data.table