EdinPC
EdinPC

Reputation: 33

How to Create Dynamic Variable Names in a For Loop in R

I have a dataset/table (called behavioural) with data from 24 participants - these are named in the format: 's1' to 's24'.

The first 6 rows in the table/dataset:

head(behavioural)[c(1,17)]
   subj     recognition_order
1   s1                 2
2   s1                 6
3   s1                 7
4   s1                 8
5   s1                 9
6   s1                10

I want to create a subset for each participant and order each of these subsets by the variable recognition_order

I have created a loop to do this:

behavioural <- read.table("*my file path*\behavioral.txt", header = TRUE)

subj_counter <- 1


for(i in 1:24) {
subject <- paste("s", subj_counter, sep = "")
subset_name <- paste(subject, "_subset", sep="")

[subset_name] <- behavioural[which(behavioural$subj  == subject), ]
[subset_name] <- subset_name[order(subset_name$recognition_order),]

subj_counter = subj_counter + 1

print(subset_name)
print(subj_counter)
}

And I'm pretty sure the logic is solid, except when I run the loop, it does not create 24 subsets. It just creates 1 - s24_subset.

What do I need to do to the bit before "<-" in these 2 lines of code?

[subset_name] <- behavioural[which(behavioural$subj  == subject), ]
[subset_name] <- subset_name[order(subset_name$recognition_order),]

Because [subset_name] isn't working.

I want the [subset_name] to be dynamic - i.e. each time the loop runs, its value changes and it creates a new subset/variable each time.

I have seen things online about the assign() function but I'm not quite sure how to implement this into my loop?

Thank you in advance!

Upvotes: 1

Views: 16086

Answers (3)

shjj08
shjj08

Reputation: 31

for(i in 1:5) {
  assign(paste0("test_",i),i) 
}
test_list <- mget(ls(pattern = "test_"))`

I hope you get a good answer. There is a good way to create an assign function and to bind this pattern in mget. I've outlined a lot of questions for R and Python about dynamically generating variables. Attached to the following link. - Creating Variables Dynamically (R, Python)

Upvotes: 3

IRTFM
IRTFM

Reputation: 263471

If you want to order the items inside the results of a split than just use lapply to pass the needed function calls to do the ordering on a single dataframe at a time (which are re-bundled together by lapply after the ordering:

my_split_list <- split(behavioural, behavioural$subj)
ord.list <- lapply( my_split_list, function(d){ 
                   d[ order(d[['recognition_order']]) , ] }

This is a common paradigm called "split-apply-combine": "The Split-Apply-Combine Strategy for Data Analysis" https://www.jstatsoft.org/article/view/v040i01/v40i01.pdf

Upvotes: 4

93i7hdjb
93i7hdjb

Reputation: 1196

You can accomplish this with eval() and parse(), like so:

eval(parse(text = paste(subset_name, "<- subset_name[order(subset_name$recognition_order),]", sep = '')))

Upvotes: 0

Related Questions