Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R对列索引_R - Fatal编程技术网

R对列索引

R对列索引,r,R,假设我有两个矩阵,A和B: mth <- c(rep(1:5,2)) day <- c(rep(10,5),rep(11,5)) hr <- c(3,4,5,6,7,3,4,5,6,7) v <- c(3,4,5,4,3,3,4,5,4,3) A <- data.frame(cbind(mth,day,hr,v)) year <- c(2008:2012) mth <- c(1:5) B <- data.frame(cbind(ye

假设我有两个矩阵,A和B:

mth <- c(rep(1:5,2))
day <- c(rep(10,5),rep(11,5)) 
hr <- c(3,4,5,6,7,3,4,5,6,7)  
v <- c(3,4,5,4,3,3,4,5,4,3)  
A <- data.frame(cbind(mth,day,hr,v))

year <- c(2008:2012)
mth <- c(1:5)  
B <- data.frame(cbind(year,mth)) 

mth
A2最简单的解决方案可能是使用
merge
,这在很多方面相当于sql连接:

merge(A,B)
#-----
merge(A, B)
   mth day hr v year
1    1  10  3 3 2008
2    1  11  3 3 2008
3    2  11  4 4 2009
4    2  10  4 4 2009
5    3  11  5 5 2010
6    3  10  5 5 2010
7    4  11  6 4 2011
8    4  10  6 4 2011
9    5  10  7 3 2012
10   5  11  7 3 2012
您也可以像这样使用
match
替换mth:

A$mth <- B[match(A$mth, B$mth),1]
#-----
    mth day hr v
1  2008  10  3 3
2  2009  10  4 4
3  2010  10  5 5
4  2011  10  6 4
5  2012  10  7 3
6  2008  11  3 3
7  2009  11  4 4
8  2010  11  5 5
9  2011  11  6 4
10 2012  11  7 3

A$mth也许只有我一个人,但根本不清楚你想要什么。你所说的
change
是指
A
中的第mth列与
B
中的
year
?谢谢,这正是我想要的。
merge(A,B)
#-----
merge(A, B)
   mth day hr v year
1    1  10  3 3 2008
2    1  11  3 3 2008
3    2  11  4 4 2009
4    2  10  4 4 2009
5    3  11  5 5 2010
6    3  10  5 5 2010
7    4  11  6 4 2011
8    4  10  6 4 2011
9    5  10  7 3 2012
10   5  11  7 3 2012
A$mth <- B[match(A$mth, B$mth),1]
#-----
    mth day hr v
1  2008  10  3 3
2  2009  10  4 4
3  2010  10  5 5
4  2011  10  6 4
5  2012  10  7 3
6  2008  11  3 3
7  2009  11  4 4
8  2010  11  5 5
9  2011  11  6 4
10 2012  11  7 3