首页 > 解决方案 > 在r中的循环内更改“字符向量”的名称

问题描述

我在 R 中工作,我有几个名为`sample 1`,的列表`sample 2`(在反引号内),我想将它们中的每一个分配给一个带有相应样本编号的变量,并带有一个循环。问题是我无法在反引号内分配 i 。有谁知道如何修改反引号名称中的循环?

>#example of one of the lists

> print(`sample 1`)

[1] "New AS Plate 21_AS Plate_Sample 1_100.fcs" "New AS Plate 21_AS Plate_Sample 1_25.fcs" 
[3] "New AS Plate 21_AS Plate_Sample 1_250.fcs" "New AS Plate 21_AS Plate_Sample 1_50.fcs" 
[5] "New AS Plate 21_AS Plate_Sample 1_500.fcs"

>#function i would like to loop

> flowdata1= print(`sample 1`)

> flowdata1

[1] "New AS Plate 21_AS Plate_Sample 1_100.fcs" "New AS Plate 21_AS Plate_Sample 1_25.fcs" 
[3] "New AS Plate 21_AS Plate_Sample 1_250.fcs" "New AS Plate 21_AS Plate_Sample 1_50.fcs" 
[5] "New AS Plate 21_AS Plate_Sample 1_500.fcs"

>#loop that doesn´work

> for(i in 1:18) {
+   assign(paste0("flowdata", i), print(`sample i`))}

print( sample i) 中的错误:找不到对象“样本 i”

我不确定是否有另一种方法来创建这些列表sample x,以便将它们命名为 sample x。我用一个循环创建了它们,该循环划分了一个包含 18 个子列表的列表,并从一个子列表中分配了样本名称。请注意,我不想为这些新列表指定迭代编号 (i) 的名称,因为它们的顺序不连续...

> for(i in 1:length(split.names)) {                   
  assign(names(split.names[i]), split.names[[i]])}

> print(sample 1)

错误:“打印(样本 1”)中出现意外的数字常量

> print(`sample 1`)

[1] "New AS Plate 21_AS Plate_Sample 1_100.fcs" "New AS Plate 21_AS Plate_Sample 1_25.fcs" 
[3] "New AS Plate 21_AS Plate_Sample 1_250.fcs" "New AS Plate 21_AS Plate_Sample 1_50.fcs" 
[5] "New AS Plate 21_AS Plate_Sample 1_500.fcs"

所以我最终得到这个变量名的方式是:

#list with 90 names

> length(sample.names.dilutions)

[1] 90

#example of names in list

> head(sample.names.dilutions)

[1] "New AS Plate 21_AS Plate_Sample 1_100.fcs"  "New AS Plate 21_AS Plate_Sample 1_25.fcs"  
[3] "New AS Plate 21_AS Plate_Sample 1_250.fcs"  "New AS Plate 21_AS Plate_Sample 1_50.fcs"  
[5] "New AS Plate 21_AS Plate_Sample 1_500.fcs"  "New AS Plate 21_AS Plate_Sample 10_100.fcs"

> #divide  list in 18 sublists applying split() function

> num.samples<- 18
> split.names <- split(sample.names.dilutions, cut(seq_along(sample.names.dilutions), num.samples, labels = FALSE))


> #create list of sample names with non consecutive numbers
> prefix <- "sample"
> suffix <- c(1,10:18,2:9)
> sample.names <- paste(prefix,suffix)

> # assign names to sublist
> names(split.names) <- sample.names

> # assign function within loop to create sample names with  specific sublist names
> for(i in 1:length(split.names)) {                   
+   assign(names(split.names[i]), split.names[[i]])}


标签: rloopsfor-loopassignbackticks

解决方案


推荐阅读