Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从R中的给定列滑动列_R - Fatal编程技术网

从R中的给定列滑动列

从R中的给定列滑动列,r,R,我收到的一些数据似乎是veeery糟糕的格式,所以我在R中逐列格式化它们 df <- read.table("path/to/file", sep = ' ', header = F, fill = T, stringsAsFactors = F) 如何将第一行移到左侧,以便获得以下结果: V1 V2 V3 V4 V5 column1 column2 column3 column4 column

我收到的一些数据似乎是
veeery
糟糕的格式,所以我在R中逐列格式化它们

df <- read.table("path/to/file", sep = ' ', header = F, fill = T, stringsAsFactors = F)
如何将
第一行
移到左侧,以便获得以下结果:

V1        V2         V3          V4          V5 
column1   column2    column3     column4     column5

不是很高效或优雅,但正是您所要求的(仅第一排):


df我猜一列中有多行没有对齐。您可以提取并对齐这些列,然后将它们与数据集的其余部分重新绑定

我的代码:

require(dplyr)

df<-data.frame(row=LETTERS[1:4],
           V1=rep(1,4),
           V2=rep(2,4),
           V3=c("NA","3","NA","3"),
           V4=c("3","4","3","4"),
           V5=c("4","5","4","5"),
           V6=c("5","NA","5","NA"))
df

# Identify rows to shift
shift_rows <- which(with( df, df$V3=="NA"))

#Extract and shift the identified rows
dfshifted<- df  %>% "["(.,shift_rows,) %>% mutate(V3=V4,V4=V5,V5=V6)

# Extract rows requiring no shifting
dfunshifted<- df[-shift_rows,]

# Bind them
df<-rbind(dfshifted,dfunshifted,make.row.names = F)

# Order the rows
df<- df[order(df$row),]

df$V6<- NULL

df
require(dplyr)

df“逐列格式化”?你们有几排?你真的只有五列吗?是否只想删除NA值?或者你想删除整列?也许这可以在“读取数据”步骤中解决-你能显示文件的前几行吗?
df <- read.csv(text = "column1 column2 NA column3 column4 column5", sep = " ", header = F, stringsAsFactors = F)
df
df[1, 3:5] <- df[1, 4:6]
df$V6 <- NULL                   # delete the last column
# Alternative: df[1, 6] <- NA   # just set the cell to NA
df
require(dplyr)

df<-data.frame(row=LETTERS[1:4],
           V1=rep(1,4),
           V2=rep(2,4),
           V3=c("NA","3","NA","3"),
           V4=c("3","4","3","4"),
           V5=c("4","5","4","5"),
           V6=c("5","NA","5","NA"))
df

# Identify rows to shift
shift_rows <- which(with( df, df$V3=="NA"))

#Extract and shift the identified rows
dfshifted<- df  %>% "["(.,shift_rows,) %>% mutate(V3=V4,V4=V5,V5=V6)

# Extract rows requiring no shifting
dfunshifted<- df[-shift_rows,]

# Bind them
df<-rbind(dfshifted,dfunshifted,make.row.names = F)

# Order the rows
df<- df[order(df$row),]

df$V6<- NULL

df