Amin Ba
Amin Ba

Reputation: 2436

how to assign vector to a subset of a column of a dataframe in R?

I have a dataframe. Suppose it has 15 rows. I want to assign a vector with length 12 to the rows 1 to 12 of one of its columns. How to do that?

month <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
DF <- c(0.2, 0.3, 0.5, 0.9, 0.8, 0.7, 1.2, 1.4, 1.5, 0.6, 0.4, 1, 0.4, 0.8, 1.3)

b <- c(1, 2, 1, 4, 1, 1, 1, 1, 3, 1, 1, 1)

df <- data.frame(DF)
df['cum_pd'] <- NA
df['marg_pd'] <- NA
rownames(df) <- month
df[1:12, "cum_pd"] <- b   # This part is my question

Upvotes: 1

Views: 92

Answers (1)

geoff
geoff

Reputation: 952

Pretty contrived but this will work for arbitrary lengths of df and b assuming you're always setting the first n rows where n = len(b).

df$cum_pd <- c(b, rep(NA, nrow(df) - length(b)))

That said, this type of data editing is dubious code at best.

Upvotes: 2

Related Questions