Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how do I set the first values of a long vector to the values of a shorter one?

In R, how can I overwrite the first values of a long vector with values obtained from a file, where the file contains possibly fewer values?

Example:

# fill with n=100 values
vec1 <- runif(100)

# read m values, where m <= n
vec2 <- scan("myfile", sep="\n")

# now want to set the first m values of vec1 
# to the values in vec2

I could walk through vec2 and copy the values into vec1, but I think there should be a more efficient way?

like image 374
Frank Avatar asked Feb 13 '10 20:02

Frank


People also ask

How do you sort a vector from high to low in R?

sort() function in R is used to sort a vector. By default, it sorts a vector in increasing order. To sort in descending order, add a “decreasing” parameter to the sort function.

How do you change a value in a vector in R?

To change the value of a vector item, we refer to their index number or position in the given vector inside brackets [] . We then assign it to a new value.

How do I order greatest to least in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do I create a specific length vector in R?

To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector.


1 Answers

R> set.seed(1)
R> vec1 <- runif(100)
R> vec2 <- 1:20

R> vec1[1:length(vec2)] <- vec2
R> vec1
  [1]  1.00000  2.00000  3.00000  4.00000  5.00000  6.00000  7.00000  8.00000
  [9]  9.00000 10.00000 11.00000 12.00000 13.00000 14.00000 15.00000 16.00000
 [17] 17.00000 18.00000 19.00000 20.00000  0.93471  0.21214  0.65167  0.12556
 [25]  0.26722  0.38611  0.01339  0.38239  0.86969  0.34035  0.48208  0.59957
 [33]  0.49354  0.18622  0.82737  0.66847  0.79424  0.10794  0.72371  0.41127
 [41]  0.82095  0.64706  0.78293  0.55304  0.52972  0.78936  0.02333  0.47723
 [49]  0.73231  0.69273  0.47762  0.86121  0.43810  0.24480  0.07068  0.09947
 [57]  0.31627  0.51863  0.66201  0.40683  0.91288  0.29360  0.45907  0.33239
 [65]  0.65087  0.25802  0.47855  0.76631  0.08425  0.87532  0.33907  0.83944
 [73]  0.34668  0.33377  0.47635  0.89220  0.86434  0.38999  0.77732  0.96062
 [81]  0.43466  0.71251  0.39999  0.32535  0.75709  0.20269  0.71112  0.12169
 [89]  0.24549  0.14330  0.23963  0.05893  0.64229  0.87627  0.77891  0.79731
 [97]  0.45527  0.41008  0.81087  0.60493
like image 51
rcs Avatar answered Sep 24 '22 20:09

rcs