在数据框中输入 NA
Input NAs in a dataframe
我想在设置特定行数的数据框中输入 NAs
。假设我想要两行 NAs
这是我的输入:
df <- "col1 col2 col3"
df <- read.table(text=df, header=T)
> ncol(df)
[1] 3
下面是我的预期输出
dfout <- "col1 col2 col3
NA NA NA
NA NA NA"
dfout <- read.table(text=dfout, header=T)
> ncol(dfout)
[1] 3
> nrow(dfout)
[1] 2
有什么想法吗?谢谢
怎么样
dfout <- df
# dfout[c(1,2),] <- c(NA, NA, NA) # not necessary - see comment below
dfout[c(1,2),] <- NA
dfout
# col1 col2 col3
# 1 NA NA NA
# 2 NA NA NA
通过在第二行设置 dfout
行索引,您应该能够完成这项工作。
我们复制'NA' 2次,即需要的nrows,转换为list
,根据'df'中子串的数量复制'3',设置名称'list' 和 'df' 在使用 scan
提取单个元素并转换为 'data.frame'.
之后
data.frame(setNames(rep(list(rep(NA,2)),3), scan(text=df, sep='', what='')))
为了更好的解释,将一行转换为小块。
v1 <- scan(text=df, sep='', what='')#extract individual elements
nR <- 2 #specify the nrows
nC <- length(v1) #ncols based on the length of 'v1'
lst <- rep(list(rep(NA, nR)), nC) #replicate NA.
names(lst) <- v1 #set the 'names' of 'list'
data.frame(lst) #convert to 'data.frame'
数据
df <- "col1 col2 col3"
我想在设置特定行数的数据框中输入 NAs
。假设我想要两行 NAs
这是我的输入:
df <- "col1 col2 col3"
df <- read.table(text=df, header=T)
> ncol(df)
[1] 3
下面是我的预期输出
dfout <- "col1 col2 col3
NA NA NA
NA NA NA"
dfout <- read.table(text=dfout, header=T)
> ncol(dfout)
[1] 3
> nrow(dfout)
[1] 2
有什么想法吗?谢谢
怎么样
dfout <- df
# dfout[c(1,2),] <- c(NA, NA, NA) # not necessary - see comment below
dfout[c(1,2),] <- NA
dfout
# col1 col2 col3
# 1 NA NA NA
# 2 NA NA NA
通过在第二行设置 dfout
行索引,您应该能够完成这项工作。
我们复制'NA' 2次,即需要的nrows,转换为list
,根据'df'中子串的数量复制'3',设置名称'list' 和 'df' 在使用 scan
提取单个元素并转换为 'data.frame'.
data.frame(setNames(rep(list(rep(NA,2)),3), scan(text=df, sep='', what='')))
为了更好的解释,将一行转换为小块。
v1 <- scan(text=df, sep='', what='')#extract individual elements
nR <- 2 #specify the nrows
nC <- length(v1) #ncols based on the length of 'v1'
lst <- rep(list(rep(NA, nR)), nC) #replicate NA.
names(lst) <- v1 #set the 'names' of 'list'
data.frame(lst) #convert to 'data.frame'
数据
df <- "col1 col2 col3"