alisa alisa - 30 days ago 9
R Question

Convert to a Class Date but Add to a Data Frame Later On in R

Im trying to add a column to the existing data frame with dates (2010-01-03, 2010-01-02, .. ), but so it says which day of the week the date is (Sunday, Monday..). I had issues converting "to class 'Date'" and making the column like a data frame instead of just characters.

I got my dataframe from here (2009-01-03 to 2010-01-02)

chart_2009 <- read.csv('BCHAIN-AVBLS (3).csv')
chart_2009_days = data.frame(date=c(chart_2009[1]))
chart_2009_days["2009 Days of the Week"] <- NA
chart_2009_days[2] <- weekdays(as.Date(chart_2009[1]))

Answer Source

Adding a column to a data.frame is as simple as

## create a dummy data.frame
df <- data.frame(date = c("2010-01-03", "2010-01-02"))
df
#         date
# 1 2010-01-03
# 2 2010-01-02

## add a new column
df$newColumn <- c("new", "column")
df
#         date newColumn
# 1 2010-01-03       new
# 2 2010-01-02    column

So there's no need for you to create a new object chart_2009_days, you can just append the column directly

chart_2009$days <- weekdays(as.Date(chart_2009[, 1]))

Noting that it's often better to reference the columns by name, rather than number, so it would be better to do

## I haven't seen your actual data so I'm just guessing the column name here
chart_2009$days <- weekdays(as.Date(chart_2009[, "date_column"]))