Skip to content

Dataframe modification

4 messages · Sachin J, Gabor Grothendieck

#
Here are two solutions:


A <- 1:8
B <- c(1,2,4,7,8)
C <- c(5,3,10,12,17)

# solution 1 - assignment with subscripting
DF <- data.frame(A, B = A, C = 0)
DF[A %in% B, "C"] <- C

# solution 2 - merge
DF <- with(merge(data.frame(A), data.frame(B, C), by = 1, all = TRUE),
        data.frame(A, B = A, C = ifelse(is.na(C), 0, C)))
On 8/21/06, Sachin J <sachinj.2006 at yahoo.com> wrote:
#
I think the first one still works in that case.
If reordering the rows is ok then the second one works too.

A <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12)
B <- c(1,2,4,7,8)
C <- c(5,3,10,12,17)

# solution 1 - assignment with subscripting
DF <- data.frame(A, B = A, C = 0)
DF[A %in% B, "C"] <- C
DF

# solution 2 - merge
DF <- with(merge(data.frame(A), data.frame(B, C), by = 1, all = TRUE,
        sort = FALSE), data.frame(A, B = A, C = ifelse(is.na(C), 0, C)))
DF
On 8/21/06, Sachin J <sachinj.2006 at yahoo.com> wrote: