Reputation: 309
How can I assign changing variable name to a changing variable name? I've seen similar questions but they are about assigning values to changing variable names. I have a list of variables named like "house1", " house2", etc. Each has a value assigned to it. E.g. house1 = 1 dollar, house2 = 50 dollars, etc. I want to create variables of type "building1", "building2", etc. and assign each "house" to a corresponding "building". So, I want to have in the end building1 = 1 dollar, building2 = 50 dollars, etc.
for(i in 1:15)
{
name_house <- paste("house", i, sep = "")
name_building <- paste("building",i, sep="")
assign(name_house, name_building)
}
I know someone would suggest creating a list of variables which contains all the buildings, but houses were already set as different variables before me, and I was asked to do building in the same way.
Upvotes: 0
Views: 648
Reputation: 388982
I have taken houses
and its corresponding values in a data.frame
. See, if this works for you,
houses <- c("house1", "house2", "house3", "house4", "house5")
name_house <- c(1, 2, 3, 4, 5)
df <- data.frame(houses, name_house)
> df
#houses name_house
#1 house1 1
#2 house2 2
#3 house3 3
#4 house4 4
#5 house5 5
Then replacing the values of house
with buildings
df$houses <- gsub("house", "building", df$houses)
> df
# houses name_house
#1 building1 1
#2 building2 2
#3 building3 3
#4 building4 4
#5 building5 5
Upvotes: 1
Reputation: 99331
If you begin with this -
( x <- setNames(paste(1:4, "dollars"), paste0("house", 1:4)) )
# house1 house2 house3 house4
# "1 dollars" "2 dollars" "3 dollars" "4 dollars"
Then you can use the following to create an identical vector with different names
setNames(x, sub("house", "building", names(x), fixed = TRUE))
# building1 building2 building3 building4
# "1 dollars" "2 dollars" "3 dollars" "4 dollars"
Upvotes: 2