【问题标题】:Shift values of multiple columns in data frame in r在r中移动数据框中多列的值
【发布时间】:2019-11-13 16:53:19
【问题描述】:

我有一个如下数据框,其中一些值针对某些列进行了移动:

 time    age    gender   day     ID
2018-01  47      male    mon     24
2018-02  NA       35     male    tue   45
2018-03  23     female   wed     45
2018-04  NA       61    female   mon   31

我想移动年龄为“NA”的列值并使它们像其他行一样。你能告诉我该怎么做吗?

【问题讨论】:

    标签: r shift


    【解决方案1】:

    对我来说,您似乎没有data.frame。看起来您有一个要读取的文本文件。如果是这种情况,您可以使用readLines 读取它,然后使用gsub 删除NA,然后您可以使用创建data.frame read.table.

    #Read the lines as they are
    x <- readLines(con=textConnection(" time    age    gender   day     ID
    2018-01  47      male    mon     24
    2018-02  NA       35     male    tue   45
    2018-03  23     female   wed     45
    2018-04  NA       61    female   mon   31"))
    
    x  <- gsub("NA","",x) #Remove NA
    x <- read.table(header=TRUE, text=x) #create data.frame
    x
    #     time age gender day ID
    #1 2018-01  47   male mon 24
    #2 2018-02  35   male tue 45
    #3 2018-03  23 female wed 45
    #4 2018-04  61 female mon 31
    

    【讨论】:

      【解决方案2】:

      让我们首先生成您的数据。

      data <- data.frame(
        time = c("2018-01", "2018-02", "2018-03", "2018-04"),
        age = c(47, NA_integer_, 23, NA_integer_),
        gender = c("male", 35, "female", 61),
        day = c("mon", "male", "wed", "female"),
        ID = c(24, "tue", 45, "mon"),
        null = c("", 45, "", 31),
        stringsAsFactors = FALSE
      )
      

      然后您可以通过执行以下操作使用data.table 包来解决您的问题:

      library(data.table)
      setDT(data)
      
      data[is.na(age), `:=`(
        age = as.double(gender),
        gender = day,
        day = ID,
        ID = null
      )][, null:=NULL]
      
      data[]
      ##        time age gender day ID
      ##  1: 2018-01  47   male mon 24
      ##  2: 2018-02  35   male tue 45
      ##  3: 2018-03  23 female wed 45
      ##  4: 2018-04  61 female mon 31
      

      【讨论】:

        【解决方案3】:

        您可以使用一些 for 循环来解决这个问题。 data 是数据框(已经变成了对象)

        for (i in 1:nrow(data)) {
        
         if (is.na(data$age[i])) {
          for (m in 3:6) { #starting by gender in column 3
           data[i, (m - 1)] <- data[i, m] #bring the value that lies in the next column to the preceding one
          }
         }
        }
        
        data <- data[, -ncol(data)] #to erase the remaining column
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-13
          • 2019-10-31
          • 1970-01-01
          • 2014-11-17
          • 2016-01-03
          • 2013-10-09
          • 1970-01-01
          相关资源
          最近更新 更多