Reputation: 869
I would like to input NAs
in a dataframe setting a specific number of rows. Let´s suppose that I would like two rows of NAs
This is my input:
df <- "col1 col2 col3"
df <- read.table(text=df, header=T)
> ncol(df)
[1] 3
And below is my expected output
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
Any ideas? Thank you
Upvotes: 1
Views: 92
Reputation: 60321
What about
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
by setting the dfout
row indices in the second line, you should be able to do the job.
Upvotes: 2
Reputation: 886938
We replicate the 'NA' 2 times i.e the nrows required, convert to list
, replicate '3' based on the number of substrings in 'df', set the names of the 'list' with 'df' after extracting the individual elements using scan
and convert to 'data.frame'.
data.frame(setNames(rep(list(rep(NA,2)),3), scan(text=df, sep='', what='')))
Converting the one line to small chunks for better explanation.
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"
Upvotes: 2