I have a data frame with empty columns. I want to fill one row of that data frame with dates.
x <- data.frame(a = 1:2, b = rep(NA, 2), c = rep(NA, 2))
mydates <- as.Date(c("2016-01-31", "2016-02-29"))
x[1, c("b", "c")] <- mydates
x
str(x)
My dates appear in the first row as numeric values and columns b and c are numeric now. Clearly not what I want.
How about this:
x <- data.frame(a = 1:2, b = rep(NA, 2), c = rep(NA, 2))
for (v in c("b", "c")) x[[v]] <- as.Date(x[[v]])
x
str(x)
x[1, c("b", "c")] <- mydates
Although I declared my variables as dates, it's not working.
What works is:
x <- data.frame(a = 1:2, b = rep(NA, 2), c = rep(NA, 2))
x
x[1, c("b", "c")] <- mydates
x
for (v in c("b", "c")) x[[v]] <- as.Date(x[[v]])
x
str(x)
Could anyone please explain what exactly is going on and why the 3rd block of code works but the second doesn't? In fact, I am not even sure why the first block of code isn't working...
Thank you very much!