user3091668
user3091668

Reputation: 2310

Replacing a number by character with apply depending of the data-frame row

I would like to replace a string (number '2' in my example) in a data-frame differently based on the row number. This is my input:

df <- "2 2 2 3
       3 3 2 1"
df <- read.table(text=df)

This would be my expected output:

dfout <- "1R 1R 1R 3
       3 3 2R 1"
dfout <- read.table(text=df)

Therefore, the number '2' should be replace by '1R' in the first row, by '2R' in the second row and so on in larger matrices (my real data has more than 1000 rows). I tried the below code without success:

apply(g1x, 1, function(x) gsub("2", nrow(x), x))

I would be glad for any help here.

Upvotes: 0

Views: 117

Answers (4)

lmo
lmo

Reputation: 38500

Here is as base R method using whichwith the arr.ind argument. It is similar in spirit to thelatemail's method.

pos <- which(df == 2, arr.ind=TRUE)
df[pos] <- paste0(pos[,1], "R")

this returns

df
  V1 V2 V3 V4
1 1R 1R 1R  3
2  3  3 2R  1

Upvotes: 1

Sotos
Sotos

Reputation: 51592

Here is an idea using sapply from base R,

 as.data.frame(t(sapply(seq(nrow(df)), function(i) 
                                       replace(df[i,], df[i,] == 2, paste0(i, 'R')))))

which gives,

  V1 V2 V3 V4
1 1R 1R 1R  3
2  3  3 2R  1

Upvotes: 3

simone
simone

Reputation: 577

Using data.table

library(data.table)

df <- "2 2 2 3
       3 3 2 1"
df <- data.table(read.table(text=df))

mycols <- names(df)
df[, (mycols) := lapply(.SD, function(x) ifelse(x==2, paste0(df[,.I], "R"),x)), .SDcols = mycols]

Upvotes: 0

thelatemail
thelatemail

Reputation: 93813

A variation on @sotos' answer:

replace(df, df==2, paste0(row(df)[df==2], "R") 

#  V1 V2 V3 V4
#1 1R 1R 1R  3
#2  3  3 2R  1

Equivalent to the replacement form of:

df[df==2] <- paste0(row(df)[df==2], "R")

Upvotes: 4

Related Questions