1

I refer to How to rename a single column in a data.frame?

# df = dataframe # old.var.name = The name you don't like anymore # new.var.name = The name you want to get names(df)[names(df) == 'old.var.name'] <- 'new.var.name' 

I want to use this way(or other rename way?)

names(df)[names(df) == 'old.var.name'] <- 'new.var.name' 

lapply for multi-layer list to rename single column, but I don't know how it iterate for sublist(such as following iris1, iris2 and iris3), let sublist rename column 'Species' to 'newSpecies'.

(If you know relevant tutorials on lapply processing multi-layer list/dataframe, you can also recommend it to me.)

irisData <- list(iris1 = iris, iris2 = iris, iris3 = iris) colnames(irisData$iris1) #[1] "Sepal.Length" "Sepal.Width" #[3] "Petal.Length" "Petal.Width" #[5] "Species" 

1 Answer 1

1

You can use lapply like this.

> irisData <- lapply(irisData, \(x) {names(x)[names(x) == 'Species'] <- 'newSpecies'; x}) > lapply(irisData, head, 2) $iris1 Sepal.Length Sepal.Width Petal.Length Petal.Width newSpecies 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa $iris2 Sepal.Length Sepal.Width Petal.Length Petal.Width newSpecies 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa $iris3 Sepal.Length Sepal.Width Petal.Length Petal.Width newSpecies 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 

Data:

irisData <- list(iris1=iris, iris2=iris, iris3=iris) 
Sign up to request clarification or add additional context in comments.

2 Comments

May I ask '; x' mean? I can't find any relevant explanation, or maybe I'm searching for wrong keywords
@ninaPeng You could think of ; as a new line operator, first the names of x are changed, then the entire x is returned. This is kinda shorthand, you could also use two lines instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.