Is there a way to scale one value to a fixed value and the other value to the corresponding scaled value. I was not able to use scale method in R as it needs a range.
For eg,
ID X Y
1 25 25
2 20 40
3 10 50
4 50 20
I need to scale the Y value to a fixed value of 100. Correspondingly X value should be scaled accordingly.
ID X Y
1 100 100
2 50 100
3 20 100
4 250 100
If your data is
id <- c(1,2,3,4)
X <- c(25,20,10,50)
Y <- c(25,40,50,20)
df <- data.frame(id,X,Y)
you could try
df$X <- df$X*100/df$Y
df$Y <- 100
# > df
# id X Y
# 1 1 100 100
# 2 2 50 100
# 3 3 20 100
# 4 4 250 100
Presumably you may also consider having a quick look at the scalefunction available in the base package. For instance, if you wish to scale part of the data frame, you could:
data("mtcars")
test <- scale(x = mtcars[,2:ncol(mtcars)], scale = TRUE)
You could easily modify the syntax further setting the base and centre so the obtained scales matches your requirements:
tst_mpg <- scale(x = mtcars$mpg, scale = 1, center = 0.5)
Related
Ahoy,
below is a df similar to the one I have to work with but way smaller:
(I left out a lot of rows to make it easier on the eyes.)
x y variable values
1 1 5 a 9
2 2 5 a 2
3 3 5 a 9
4 4 5 a 8
5 5 5 a 4
...
22 2 1 a 7
23 3 1 a 9
24 4 1 a 7
25 5 1 a 10
26 1 5 b 7
27 2 5 b 8
...
48 3 1 b 8
49 4 1 b 7
50 5 1 b 2
The df above is created by an fluorescence plate reader which scans light intensity within an area by dividing it in into 25 sectors (5x5) and measuring each sector individually giving one value each. The order of measurements is upper left corner sector first and lower right corner sector last. To make it more graphical:
01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Filling in the values from the df given above (+coordinates), it would look like this:
(5) ___ 9 - 2 - 9 - 8 - 4
(4) ___ 7 - 7 - 2 - 5 - 3
(3) ___ 5 - 4 - 7 - 8 - 9
(2) ___ 6 - 6 - 3 - 5 - 9
(1) ___ 4 - 7 - 9 - 7 - 10
(y^,x>) (1) (2) (3) (4) (5)
What I need is to read out the max value for each variable and calculate the mean of this value and the (up to) 9 fields surrounding it. In the area/"variable" above("a") the highest value of a sector is 10 in the lower right corner, which is surrounded by the values 5,9 and 7. Hence the Result I am looking for for variable "a" is 7.75 ((5+9+7+10)/4).
I imagine the code to resemble something like this (I am aware that this is not how you write r, but I don't know better):
mean(max value within variable,value at x(of max value within variable)-1,y(of max value within variable)),value at x(of max value within variable)-1,y(of max value within variable)+1) .....
The next issue challenge is that the instrument will perform scans of 96 areas (="variables"). And ideally I need a solution that automatically gives me this special mean value for every/all variables without me having to write the almost identical code 96times.
I know this is asking a bit much but I have been working on it for a while and I just cant come up with a solution or even a good way of googling it.
Thank you very much for any help!
Tim,
Ps: Using this R code creates a random version of the df I present above:
df <- data.frame(x = c(1:5), y = rep(c(5:1), each=5),variable = rep(c("a", "b"), each=25 ), values = floor(runif(50, min=1, max=10)))
This updated answer will provide the mean value of the maximum value and it's up to 9 surrounding values, within each variable group.
library(dplyr)
# Create the function
get.means <- function(df){
# Get a data frame of rows with the maximum value
max.rows <- df[df$values == max(df$values), ]
# Create an empty data frame
means.df <- data.frame(variable = character(), x = integer(), y = integer(), value = numeric(), mean = numeric(), stringsAsFactors = FALSE)
# Create an iterator for the data frame
iterator <- 1
# Loop through each row of the maximum value data frame
for(i in c(1:nrow(max.rows))){
# Get the x value for the current row
x <- max.rows$x[i]
# Get the y value for the current row
y <- max.rows$y[i]
# Set the range of x values to process based on the x coordinate
if(x == 1){
x.range <- c(1, 2)
} else if(x == 5){
x.range <- c(4, 5)
} else{
x.range <- c(x-1, x, x+1)
}
# Set the range of y values to process based on the y coordinate
if(y == 1){
y.range <- c(1, 2)
} else if(y == 5){
y.range <- c(4, 5)
} else{
y.range <- c(y-1, y, y+1)
}
# Get a matrix of the values from the original data frame, which are in both the current y and x ranges
vals <- as.matrix(df[(df$y %in% y.range) & (df$x %in% x.range), 'values'])
# Get the mean of the values
mean.val <- mean(vals)
# Insert the current variable value to the data frame for the new row
means.df[iterator, 'variable'] <- as.character(max.rows$variable[i])
# Insert the current x, y, value, and mean values for the new row
means.df[iterator, c('x','y','value', 'mean')] <- c(x, y, max.rows$values[i], mean.val)
# Increment the iterator
iterator <- iterator + 1
}
# Return the final data frame
return(means.df)
}
# Create a test data frame
df <- data.frame(x = c(1:5), y = rep(c(5:1), each=5),variable = rep(c("a", "b"), each=25 ), values = floor(runif(50, min=1, max=10)))
# Get the means for each max value within the variable grouping
df1 <- df %>%
group_by(variable) %>%
do(get.means(.))
I am basically new to using R software.
I have a list of repeating codes (numeric/ categorical) from an excel file. I need to add another column values (even at random) to which every same code will get the same value.
Codes Value
1 122
1 122
2 155
2 155
2 155
4 101
4 101
5 251
5 251
Thank you.
We can use match:
n <- length(code0 <- unique(code))
value <- sample(4 * n, n)[match(code, code0)]
or factor:
n <- length(unique(code))
value <- sample(4 * n, n)[factor(code)]
The random integers generated are between 1 and 4 * n. The number 4 is arbitrary; you can also put 100.
Example
set.seed(0); code <- rep(1:5, sample(5))
code
# [1] 1 1 1 1 1 2 2 3 3 3 3 4 4 4 5
n <- length(code0 <- unique(code))
sample(4 * n, n)[match(code, code0)]
# [1] 5 5 5 5 5 18 18 19 19 19 19 12 12 12 11
Comment
The above gives the most general treatment, assuming that code is not readily sorted or taking consecutive values.
If code is sorted (no matter what value it takes), we can also use rle:
if (!is.unsorted(code)) {
n <- length(k <- rle(code)$lengths)
value <- rep.int(sample(4 * n, n), k)
}
If code takes consecutive values 1, 2, ..., n (but not necessarily sorted), we can skip match or factor and do:
n <- max(code)
value <- sample(4 * n, n)[code]
Further notice: If code is not numerical but categorical, match and factor method will still work.
What you could also do is the following, it is perhaps more intuitive to a beginner:
data <- data.frame('a' = c(122,122,155,155,155,101,101,251,251))
duplicates <- unique(data)
duplicates[, 'b'] <- rnorm(nrow(duplicates))
data <- merge(data, duplicates, by='a')
Suppose the data frame is like this:
df <- data.frame(x = c(1,7,8,15,24,100,9,19,128))
How do I create a new variable that satisfies the following condition:
y = 1 if 1<=x<=7
y = 2 if 8<=x<=14
y = 3 if 15<=x<=21
...
y = k if 1+7*(k-1)<= x<= 7+7*(k-1)
so that I can have the new data frame like this
df <- data.frame(y = c(1,1,2,3,4,15, 2,3, 19))
I am wondering if a for loop can be applied in this case.
Via simple algebra, you can do:
df$y <- floor((df$x+6)/7)
df
# x y
# 1 1 1
# 2 7 1
# 3 8 2
# 4 15 3
# 5 24 4
# 6 100 15
# 7 9 2
# 8 19 3
# 9 128 19
In R you will often find it easier (less typing and less thinking) to use vectorized operators than for loops for simple computations like this. In this case we performed calls to +, /, and floor over a whole vector instead of looping and using them on each element.
I have a data frame that has the first column go from 1 to 365 like this
c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2...
and the second column has times that repeat over and over again like this
c(0,30,130,200,230,300,330,400,430,500,0,30,130,200,230,300,330,400,430,500...
so for every 1 value in the first column I have a corresponding time in the second column then when I get to the 2's the times start over and each 2 has a corresponding time,
occasionally I will come across
c(3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4...
c(0,30,130,200,230,330,400,430,500,0,30,130,200,230,300,330,400,430,500...
Here one of the 3's is missing and the corresponding time of 300 is missing with it.
How can I go through my entire data frame and add these missing values? I need a way for R to go through and identify any missing values then insert a row and put the appropriate value, 1 to 365, in column one and the appropriate time with it. So for the given example R would add a row in between 230 and 330 and then place a 3 in the first column and 300 in the second. There are parts of the column that are missing several consecutive values. It is not just one here and there
EDIT: Solution with all 10 times clearly specified in advance and code tidy up/commenting
You need to create another data.frame containing every possible row and then merge it with your data.frame. The key aspect is the all.x = TRUE in the final merge which forces the gaps in your data to be highlighted. I simulated the gaps by sampling only 15 of the first 20 possible day/time combinations in your.dat
# create vectors for the days and times
the.days = 1:365
the.times = c(0,30,100,130,200,230,330,400,430,500) # the 10 times to repeat
# create a master data.frame with all the times repeated for each day, taking only the first 20 observations
dat.all = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365))[1:20,]
# mimic your data.frame with some gaps in it (only 15 of 20 observations are present)
your.sample = sample(1:20, 15)
your.dat = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365), x3 = rnorm(365*10))[your.sample,]
# left outer join merge to include ALL of the master set and all of your matching subset, filling blanks with NA
merge(dat.all, your.dat, all.x = TRUE)
Here is the output from the merge, showing all 20 possible records with the gaps clearly visible as NA:
x1 x2 x3
1 1 0 NA
2 1 30 1.23128294
3 1 100 0.95806838
4 1 130 2.27075361
5 1 200 0.45347199
6 1 230 -1.61945983
7 1 330 NA
8 1 400 -0.98702883
9 1 430 NA
10 1 500 0.09342522
11 2 0 0.44340164
12 2 30 0.61114408
13 2 100 0.94592127
14 2 130 0.48916825
15 2 200 0.48850478
16 2 230 NA
17 2 330 0.52789171
18 2 400 -0.16939587
19 2 430 0.20961745
20 2 500 NA
Here are a few NA handling functions that could help you getting started.
For the inserting task, you should provide your own data using dput or a reproducible example.
df <- data.frame(x = sample(c(1, 2, 3, 4), 100, replace = T),
y = sample(c(0,30,130,200,230,300,330,400,430,500), 100, replace = T))
nas <- sample(NA, 20, replace = T)
df[1:20, 1] <- nas
df$y <- ifelse(df$y == 0, NA, df$y)
# Columns x and y have NA's in diferent places.
# Logical test for NA
is.na(df)
# Keep not NA cases of one colum
df[!is.na(df$x),]
df[!is.na(df$y),]
# Returns complete cases on both rows
df[complete.cases(df),]
# Gives the cases that are incomplete.
df[!complete.cases(df),]
# Returns the cases without NAs
na.omit(df)
I would like to aggregate an R data.frame by equal amounts of the cumulative sum of one of the variables in the data.frame. I googled quite a lot, but probably I don't know the correct terminology to find anything useful.
Suppose I have this data.frame:
> x <- data.frame(cbind(p=rnorm(100, 10, 0.1), v=round(runif(100, 1, 10))))
> head(x)
p v
1 10.002904 4
2 10.132200 2
3 10.026105 6
4 10.001146 2
5 9.990267 2
6 10.115907 6
7 10.199895 9
8 9.949996 8
9 10.165848 8
10 9.953283 6
11 10.072947 10
12 10.020379 2
13 10.084002 3
14 9.949108 8
15 10.065247 6
16 9.801699 3
17 10.014612 8
18 9.954638 5
19 9.958256 9
20 10.031041 7
I would like to reduce the x to a smaller data.frame where each line contains the weighted average of p, weighted by v, corresponding to an amount of n units of v. Something of this sort:
> n <- 100
> cum.v <- cumsum(x$v)
> f <- cum.v %/% n
> x.agg <- aggregate(cbind(v*p, v) ~ f, data=x, FUN=sum)
> x.agg$'v * p' <- x.agg$'v * p' / x.agg$v
> x.agg
f v * p v
1 0 10.039369 98
2 1 9.952049 94
3 2 10.015058 104
4 3 9.938271 103
5 4 9.967244 100
6 5 9.995071 69
First question, I was wondering if there is a better (more efficient approach) to the code above. The second, more important, question is how to correct the code above in order to obtain more precise bucketing. Namely, each row in x.agg should contain exacly 100 units of v, not just approximately as it is the case above. For example, the first row contains the aggregate of the first 17 rows of x which correspond to 98 units of v. The next row (18th) contains 5 units of v and is fully included in the next bucket. What I would like to achieve instead would be attribute 2 units of row 18th to the first bucket and the remaining 3 units to the following one.
Thanks in advance for any help provided.
Here's another method that does this with out repeating each p v times. And the way I understand it is, the place where it crosses 100 (see below)
18 9.954638 5 98
19 9.958256 9 107
should be changed to:
18 9.954638 5 98
19.1 9.958256 2 100 # ---> 2 units will be considered with previous group
19.2 9.958256 7 107 # ----> remaining 7 units will be split for next group
The code:
n <- 100
# get cumulative sum, an id column (for retrace) and current group id
x <- transform(x, cv = cumsum(x$v), id = seq_len(nrow(x)), grp = cumsum(x$v) %/% n)
# Paste these two lines in R to install IRanges
source("http://bioconductor.org/biocLite.R")
biocLite("IRanges")
require(IRanges)
ir1 <- successiveIRanges(x$v)
ir2 <- IRanges(seq(n, max(x$cv), by=n), width=1)
o <- findOverlaps(ir1, ir2)
# gets position where multiple of n(=100) occurs
# (where we'll have to do something about it)
pos <- queryHits(o)
# how much do the values differ from multiple of 100?
val <- start(ir2)[subjectHits(o)] - start(ir1)[queryHits(o)] + 1
# we need "pos" new rows of "pos" indices
x1 <- x[pos, ]
x1$v <- val # corresponding values
# reduce the group by 1, so that multiples of 100 will
# belong to the previous row
x1$grp <- x1$grp - 1
# subtract val in the original data x
x$v[pos] <- x$v[pos] - val
# bind and order them
x <- rbind(x1,x)
x <- x[with(x, order(id)), ]
# remove unnecessary entries
x <- x[!(duplicated(x$id) & x$v == 0), ]
x$cv <- cumsum(x$v) # updated cumsum
x$id <- NULL
require(data.table)
x.dt <- data.table(x, key="grp")
x.dt[, list(res = sum(p*v)/sum(v), cv = tail(cv, 1)), by=grp]
Running on your data:
# grp res cv
# 1: 0 10.037747 100
# 2: 1 9.994648 114
Running on #geektrader's data:
# grp res cv
# 1: 0 9.999680 100
# 2: 1 10.040139 200
# 3: 2 9.976425 300
# 4: 3 10.026622 400
# 5: 4 10.068623 500
# 6: 5 9.982733 562
Here's a benchmark on a relatively big data:
set.seed(12345)
x <- data.frame(cbind(p=rnorm(1e5, 10, 0.1), v=round(runif(1e5, 1, 10))))
require(rbenchmark)
benchmark(out <- FN1(x), replications=10)
# test replications elapsed relative user.self
# 1 out <- FN1(x) 10 13.817 1 12.586
It takes about 1.4 seconds on 1e5 rows.
If you are looking for precise bucketing, I am assuming value of p is same for 2 "split" v
i.e. in your example, value of p for 2 units of row 18th that go in first bucket is 9.954638
With above assumption, you can do following for not super large datasets..
> set.seed(12345)
> x <- data.frame(cbind(p=rnorm(100, 10, 0.1), v=round(runif(100, 1, 10))))
> z <- unlist(mapply(function(x,y) rep(x,y), x$p, x$v, SIMPLIFY=T))
this creates a vector with each value of p repeated v times for each row and result is combined into single vector using unlist.
After this aggregation is trivial using aggregate function
> aggregate(z, by=list((1:length(z)-0.5)%/%100), FUN=mean)
Group.1 x
1 0 9.999680
2 1 10.040139
3 2 9.976425
4 3 10.026622
5 4 10.068623
6 5 9.982733