如何从read.table访问R中的数据

时间:2015-01-27 09:19:09

标签: r

我收到了这个文本文件:

a b c d
0 2 8 9
2 0 3 4
8 3 0 2
9 4 2 0

我把这个命令放在R:

k<-read.table("d:/r/file.txt", header=TRUE)

现在我想访问第3行第4列(即2)中的值...如何访问它? 基本上我的问题是如何逐个访问表数据?我想在嵌套for循环中单独使用所有数据。 像:

for(row=0;row<4;row++)
for(col=0;col<4;col++)
print data[row][col];

2 个答案:

答案 0 :(得分:0)

您可能希望对矩阵的每个元素应用特定操作。 这是你如何做到的,一个例子

A <- matrix(1:16,4,4)
apply(A,c(1,2),function(x) {x %% 5})

整行操作

apply(A,1,function(x) sum(x^2))

答案 1 :(得分:-2)

这是你想要的吗? :

test <- read.table("test.txt", header = T, fill = T)

for(i in 1:nrow(test)){
  for(j in 1:ncol(test)) {
    print(test[i,j])
  }
}