3

I have a df like this:

           X1  X2  X3  X4
Number      4   4   4   4
Number.1    2   3   3   2

And I'd like to transform it into this:

> X1
  NA
   4
   2
  NA
   4
   3
  NA
   4
   3
  NA
   4
   2
  NA

How can I intercalate NA with my df like in the example? So far I tried with sapply(df, function(x) NA, t(Number(y))) but it retrieves an error... I know I have to use t() to transpose my df but how to add the NA in between columns to rows?

Any suggestions?

Note: I am not new to R but lately I have been having some issues... I searched all over StackOverflow but I could not find the answer.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Biostatician
  • 111
  • 5

3 Answers3

3

Here is an idea via stacking the data frame and using ind and our group indicator to add the extra rows, i.e.

s_df <- stack(df)
rbind(data.frame(values = NA, ind = NA), do.call(rbind, by(s_df, s_df$ind, rbind, NA)))[1]

which gives,

      values
1         NA
X1.1       4
X1.2       2
X1.3      NA
X2.3       4
X2.4       3
X2.31     NA
X3.5       4
X3.6       3
X3.3      NA
X4.7       4
X4.8       2
X4.3      NA

DISCLAIMER Credits go to this answer

Sotos
  • 51,121
  • 6
  • 32
  • 66
2

You could use rbind(NA, dat) and unlist with use.name = FALSE - thanks to @zx8754.

data.frame(X1 = c(unlist(rbind(NA, dat), use.name = FALSE), NA))

Result

#   X1
#1  NA
#2   4
#3   2
#4  NA
#5   4
#6   3
#7  NA
#8   4
#9   3
#10 NA
#11  4
#12  2
#13 NA

c(..., NA) appends NA at the end of the vector.

data

dat <- structure(list(X1 = c(4L, 2L), X2 = c(4L, 3L), X3 = c(4L, 3L), 
    X4 = c(4L, 2L)), .Names = c("X1", "X2", "X3", "X4"), class = "data.frame", row.names = c("Number", 
"Number.1"))
markus
  • 25,843
  • 5
  • 39
  • 58
2

Selecting out of range rows creates NA rows, then unlist:

data.frame(X1 = c(NA, unlist(dat[1:3, ], use.names = FALSE)))
#    X1
# 1  NA
# 2   4
# 3   2
# 4  NA
# 5   4
# 6   3
# 7  NA
# 8   4
# 9   3
# 10 NA
# 11  4
# 12  2
# 13 NA
zx8754
  • 52,746
  • 12
  • 114
  • 209