user330
user330

Reputation: 1290

How to add a name to a data frame and change a specific cell in R

Here is a sample of my data:

    class   gender
Yellow  12  F
Blue    14  M
red 13  F

I want to add a name for colours and then change "red" to "purple"

So I will get the following table:

Colour  class   gender
Yellow  12  F
Blue    14  M
Purple  13  F

I have used the following codes

setNames(cbind(rownames(df), df), 
          c("colour"))

But, it does not work. Thanks in advance for your help

Upvotes: 1

Views: 143

Answers (4)

djourd1
djourd1

Reputation: 479

Just in case, a data.table solution:

library(data.table)
setDT(df, keep.rownames = TRUE)  # tranform df into a data.table a change the row names into a column called rn
setnames(df, "rn", "Color")  # change the name
df[Color=='red', Color:="purple"] # change "red" to "purple"
df

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389135

Here is a base R option :

#add rowname as new column
df$Colour <- rownames(df)
#remove rowname
rownames(df) <- NULL
#replace 'red' with 'Purple'
df$Colour[df$Colour == 'red'] <- 'Purple'
df

#  class gender Colour
#1    12      F Yellow
#2    14      M   Blue
#3    13      F Purple

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102241

Hope this base R option works for you

cbind(
  Color = gsub("^red$", "Purple", row.names(df)),
  df, 
  row.names = NULL
)

which gives

   Color class gender
1 Yellow    12      F
2   Blue    14      M
3 Purple    13      F

Data

> dput(df)
structure(list(class = c(12L, 14L, 13L), gender = c("F", "M", 
"F")), class = "data.frame", row.names = c("Yellow", "Blue",
"red"))

Upvotes: 1

akrun
akrun

Reputation: 887501

We create a column with rownames_to_column and replace the 'red' values in 'Colour' column to "Purple"

library(dplyr)
library(tibble)
df1 <- df1 %>%
   rownames_to_column("Colour") %>%
   mutate(Colour = replace(Colour, Colour == "red", "Purple"))

-output

df1
#  Colour class gender
#1 Yellow    12      F
#2   Blue    14      M
#3 Purple    13      F

setNames in OP's post, requires the "Colour" along with the column names of the 'df'

setNames(cbind(rownames(df), df), 
      c("Colour", names(df)))    

data

df1 <- structure(list(class = c(12L, 14L, 13L), gender = c("F", "M", 
"F")), class = "data.frame", row.names = c("Yellow", "Blue", 
"red"))

Upvotes: 2

Related Questions