Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace value with the name of its respective column

Tags:

dataframe

r

I have a data frame:

Code    401k    CVS
101A            true
231N    true
FD54    true
99JB    
85F4    true

I'm trying to replace the "true" character values with the respective column name (e.g. "401k"). This is my desired output:

Code    401k    CVS
101A            CVS
231N    401k
FD54    401k
99JB    
85F4    401k
like image 270
Dale Kube Avatar asked Nov 02 '14 19:11

Dale Kube


People also ask

What is used to change values of columns?

We can use ALTER TABLE ALTER COLUMN statement to change the datatype of the column.

How do you replace a value in a DataFrame column in Python?

DataFrame. replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame. When inplace=True is used, it replaces on existing DataFrame object and returns None value.


2 Answers

The coding below enabled me to replace every "true" value (character) into its respective column name.

##Replace every "true" value with its respective column name
w <- which(df=="true",arr.ind=TRUE)
df[w] <- names(df)[w[,"col"]]
like image 183
Dale Kube Avatar answered Sep 25 '22 22:09

Dale Kube


This first method will do it without coercing the data to character first:

wc <- droplevels(col(df, as.factor=TRUE)[which(df == "true")])
df[levels(wc)] <- Map(factor, df[levels(wc)], labels = levels(wc))
df
#   Code  401k  CVS
# 1 101A  <NA>  CVS
# 2 231N  401k <NA>
# 3 FD54  401k <NA>
# 4 99JB  <NA> <NA>
# 5 85F4  401k <NA>

Or you can use which with the data frame indices and convert everything to character:

df[] <- lapply(df, function(x) levels(x)[x])
w <- which(df == "true", arr.ind = TRUE)
df[w] <- names(df)[w[,"col"]]
df
#   Code  401K  CVS
# 1 101A  <NA>  CVS
# 2 231N  401K <NA>
# 3 FD54  401K <NA>
# 4 99JB  <NA> <NA>
# 5 85F4  401K <NA>
like image 33
Rich Scriven Avatar answered Sep 25 '22 22:09

Rich Scriven