请考虑以下data.frame
:
structure(list(chr = c("1A", "1B", "1D", "2A", "2B", "2D"), initial =
c(210200000L,237700000L, 166200000L, 326300000L, 344400000L, 264400000L),
end = c(215800000L, 243500000L, 173800000L, 327000000L, 351300000L,
272500000L)), row.names = c(NA, 6L), class = "data.frame")
它看起来是这样的:
chr initial end
1A 210200000 215800000
1B 237700000 243500000
1D 166200000 173800000
2A 326300000 327000000
2B 344400000 351300000
2D 264400000 272500000
我想遍历此数据集的变量,以使数值范围变量像这样:
A1 <- 210200000:215800000
B1 <- 237700000:243500000
D1 <- 166200000:173800000
所以A1,B1,D1 ...依此类推,直到A7,B7,D7。
我知道我可以像这样for (i in 1:7) {...}
创建一个for循环,但是我不知道如何也可以循环遍历字符ABD
答案 0 :(得分:1)
目前尚不清楚100%遍历A,B,D和1:7的情况-您的样本数据仅迭代2,但也许只是您总体数据的一小段?
无论如何,函数list2env
在这里可能会有所帮助。您还需要一些字符串操作才能通过颠倒chr
的顺序来创建有效名称。希望这能使您走上正确的轨道:
dat <- structure(list(chr = c("1A", "1B", "1D", "2A", "2B", "2D"), initial =
c(210200000L,237700000L, 166200000L, 326300000L, 344400000L, 264400000L),
end = c(215800000L, 243500000L, 173800000L, 327000000L, 351300000L,
272500000L)), row.names = c(NA, 6L), class = "data.frame")
sequences <- lapply(1:nrow(dat), function(x) dat[x,2]:dat[x,3])
#helper function from ?strsplit
strReverse <- function(x) sapply(lapply(strsplit(x, NULL), rev), paste,
collapse="")
#you could also use make.names() instead.
names(sequences) <- strReverse(dat$chr)
#specify the global environment - creates an object from each item in the list
list2env(sequences, envir = .GlobalEnv)
在此之后运行ls()
将产生以下结果:
> ls()
[1] "A1" "A2" "B1" "B2" "D1" "D2" "dat" "sequences" "strReverse"