>titletool<-read.csv("TotalCSVData.csv",header=FALSE,sep=",")
> class(titletool)
[1] "data.frame"
>titletool[1,1]
[1] Experiment name : CONTROL DB AD_1
>t<-titletool[1,1]
>t
[1] Experiment name : CONTROL DB AD_1
>class(t)
[1] "character"
现在我想创建一个名为“实验名称:CONTROL DB AD_1”的对象(矢量),如果可能的话甚至更好控制数据库AD_1
谢谢
答案 0 :(得分:1)
使用assign
:
varname <- "Experiment name : CONTROL DB AD_1"
assign(varname, 3.14158)
get("Experiment name : CONTROL DB AD_1")
[1] 3.14158
您可以使用正则表达式sub
或gsub
从字符串中删除一些文字:
cleanVarname <- sub("Experiment name : ", "", varname)
assign(cleanVarname, 42)
get("CONTROL DB AD_1")
[1] 42
但是让我警告你这是不寻常的事情。
这里是龙。
答案 1 :(得分:1)
如果我理解正确,你有一堆CSV文件,每个文件都包含多个实验,以“实验...”模式命名。您现在想要以有效的方式将这些“实验”中的每一个读入R中。
这是一个不那么漂亮(但也不那么丑陋)的功能,可能会让你开始朝着正确的方向前进。
该功能基本上是在CSV中读取,识别每个新实验开始的行号,抓取实验的名称,然后循环填写具有单独数据帧的列表。它并没有真正打扰制作“R友好”的名字,我决定将输出留在列表中,因为正如Andrie指出的那样,“R有很好的工具来处理列表。”
read.funkyfile = function(funkyfile, expression, ...) {
temp = readLines(funkyfile)
temp.loc = grep(expression, temp)
temp.loc = c(temp.loc, length(temp)+1)
temp.nam = gsub("[[:punct:]]", "",
grep(expression, temp, value=TRUE))
temp.out = vector("list")
for (i in 1:length(temp.nam)) {
temp.out[[i]] = read.csv(textConnection(
temp[seq(from = temp.loc[i]+1,
to = temp.loc[i+1]-1)]),
...)
names(temp.out)[i] = temp.nam[i]
}
temp.out
}
以下是CSV文件示例。将其复制并粘贴到文本编辑器中,并将其保存为当前工作目录中的“funkyfile1.csv”。 (或者,从Dropbox中读取它:http://dl.dropbox.com/u/2556524/testing/funkyfile1.csv)
"Experiment Name: Here Be",,
1,2,3
4,5,6
7,8,9
"Experiment Name: The Dragons",,
10,11,12
13,14,15
16,17,18
这是第二张CSV。再次,复制粘贴并将其保存为当前工作目录中的“funkyfile2.csv”。 (或者,从Dropbox中读取它:http://dl.dropbox.com/u/2556524/testing/funkyfile2.csv)
"Promises: I vow to",,
"H1","H2","H3"
19,20,21
22,23,24
25,26,27
"Promises: Slay the dragon",,
"H1","H2","H3"
28,29,30
31,32,33
34,35,36
请注意,funkyfile1
没有列名,而funkyfile2
则没有。这就是函数中...
参数的用途:指定header=TRUE
或header=FALSE
。标识每组新数据的“表达式”也是funkyfile2
中的“承诺”。
现在,使用函数:
read.funkyfile("funkyfile1.csv", "Experiment", header=FALSE)
# read.funkyfile("http://dl.dropbox.com/u/2556524/testing/funkyfile1.csv",
# "Experiment", header=FALSE) # Uncomment to load remotely
# $`Experiment Name Here Be`
# V1 V2 V3
# 1 1 2 3
# 2 4 5 6
# 3 7 8 9
#
# $`Experiment Name The Dragons`
# V1 V2 V3
# 1 10 11 12
# 2 13 14 15
# 3 16 17 18
read.funkyfile("funkyfile2.csv", "Promises", header=TRUE)
# read.funkyfile("http://dl.dropbox.com/u/2556524/testing/funkyfile2.csv",
# "Experiment", header=TRUE) # Uncomment to load remotely
# $`Promises I vow to`
# H1 H2 H3
# 1 19 20 21
# 2 22 23 24
# 3 25 26 27
#
# $`Promises Slay the dragon`
# H1 H2 H3
# 1 28 29 30
# 2 31 32 33
# 3 34 35 36
去抓那些龙。
如果您的数据格式相同,则可以使用Andrie提及的lapply
解决方案以及此功能。只需列出要加载的CSV列表,如下所示。请注意,文件都需要使用与当前函数编写方式相同的“表达式”和其他参数....
temp = list("http://dl.dropbox.com/u/2556524/testing/funkyfile1.csv",
"http://dl.dropbox.com/u/2556524/testing/funkyfile3.csv")
lapply(temp, read.funkyfile, "Experiment", header=FALSE)