Replace values in dataframe of rows and columns from vectors

Viewed 200

I have a data frame with zeros:

    2015 2016 2017 2018
1     0    0    0    0 
2     0    0    0    0
3     0    0    0    0
4     0    0    0    0

I also have two vectors: 1, 3, 3, 3 (row number) and 2015, 2016, 2016, 2018 (column name). I would like to increment (+1) values of these particular row numbers and column names ([1,2015], [3,2016], [3,2016], [3,2018]), to get something like this:

    2015 2016 2017 2018
1     1    0    0    0 
2     0    0    0    0
3     0    2    0    1
4     0    0    0    0
3 Answers

Here is a vectorized option

m1 <- cbind(vec1, match(vec2, names(df)))
v1 <- ave(rep(1, length(vec1)), m1[,1], m1[,2], FUN = sum)
i1 <- !duplicated(m1)
df[m1[i1,]] <- v1[i1]

-output

df
#  2015 2016 2017 2018
#1    1    0    0    0
#2    0    0    0    0
#3    0    2    0    1
#4    0    0    0    0

data

df <- data.frame(rep(0,4),rep(0,4),rep(0,4),rep(0,4))
colnames(df) <- 2015:2018

vec1 <- c(1,3,3,3)
vec2 <- c(2015,2016,2016,2018)
for(i in 1:length(vec1){
  df[vec1[i],paste(vec2[i])] = df[vec1[i],paste(vec2[i])] + 1
}

You need to pass the column names vector as a character, or it would interpret as the 2015th column, that's why the paste()

Dummy data:

df = data.frame(rep(0,4),rep(0,4),rep(0,4),rep(0,4))
colnames(df) = 2015:2018

vec1 = c(1,3,3,3)
vec2 = c(2015,2016,2016,2018)

You can try a brute force approach like this.

#Create your data.frame
d=data.frame(matrix(0,ncol=4,nrow=4))
dimnames(d)=list( 1:4,2015:2018)

#Create your two vectors, note that the column names are characters
r=c(1,3,3,3)
cl=as.character(c(2015,2016,2016,2018))

#Loop through the vectors, locate each position in the data.frame and increment by 1
for(i in 1:length(r)){
  d[r[i],cl[i]] = d[r[i],cl[i]]+1
}

d

`

Related