r中数据帧中多列的移位值

问题描述 投票:0回答:3

我有一个数据框,如下所示,某些列的某些值已移动:

 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
3个回答
1
投票
对我来说,您看起来已经没有data.frame。看起来您有一个要读取的文本文件。如果是这种情况,您可以使用readLines读取它,然后用NA删除gsub,然后可以使用创建一个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


0
投票
首先生成您的数据。

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


0
投票
您可以使用一些for循环解决此问题。数据是数据帧(已经变成对象)

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

© www.soinside.com 2019 - 2024. All rights reserved.