for 문을 이용해 여러 이름을 가진 변수에 내용을 할당하고 싶었다.
chatgpt로 물어보니 아주 명확하게 답해준다.
| 질문
I want to Create multiple variables using the for function. show me example R code.
| 답
Sure, here's an example code in R that uses the for loop to create multiple variables:
# Create a vector of numbers
numbers <- c(1, 2, 3, 4, 5)
# Use a for loop to create multiple variables
for (i in 1:length(numbers)) {
assign(paste0("var", i), numbers[i])
}
# Check the values of the new variables
var1
var2
var3
var4
var5
In this code, we first create a vector of numbers called "numbers". We then use a for loop to iterate over each element of the vector and create a new variable with a unique name for each element. The assign function is used to create a new variable and assign it a value. The paste0 function is used to concatenate the string "var" with the current index i to create a unique variable name.
After running this code, you should see that five new variables have been created (var1, var2, var3, var4, and var5), each with a value equal to the corresponding element in the "numbers" vector.
for문까지 완벽히 적용한 예제와 assign(변수 이름, 넣을 값)함수를 바로 출력해주었다.
저 코드를 사용하니 내가 정확히 원하는건 아니지만 유용한 함수였다.
앞으로도 애용해야지ㅎㅎ