Using lapply to create new variables based on multiple conditions and subsets












2















I am trying to create a list of new variables that represent the deviations from the minimum values of variables based on subsets of another variable.



Consider the following:



df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))


I would like to create two new variables, call them x.var and y.var, that take on the deviation from the minimum value of the respective underlying variables contingent on cluster. Thus, x.var and y.var would hopefully be:



x.var y.var
-1 -3
-3 -2
0 0
-3 0
0 -1
-5 -3


I have tried unsuccessfully to use lapply with an anonymous function to accomplish this:



vars <- lapply(df[,c(2:3)],function(x) 
ifelse(df$cluster=="A",
min(df[df$cluster=="A",x])-x,
min(df[df$cluster=="B",x])-x))


I receive the following error:



Error in `[.data.frame`(df, df$cluster == "A", x) : undefined columns selected 


Any help would be much appreciated!










share|improve this question

























  • I think the 4th value of x.var should be -3 (2-5) ?

    – thelatemail
    Jan 2 at 0:26











  • You are right. Thanks for catching that. I adjusted the value.

    – Jeff
    Jan 2 at 4:00
















2















I am trying to create a list of new variables that represent the deviations from the minimum values of variables based on subsets of another variable.



Consider the following:



df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))


I would like to create two new variables, call them x.var and y.var, that take on the deviation from the minimum value of the respective underlying variables contingent on cluster. Thus, x.var and y.var would hopefully be:



x.var y.var
-1 -3
-3 -2
0 0
-3 0
0 -1
-5 -3


I have tried unsuccessfully to use lapply with an anonymous function to accomplish this:



vars <- lapply(df[,c(2:3)],function(x) 
ifelse(df$cluster=="A",
min(df[df$cluster=="A",x])-x,
min(df[df$cluster=="B",x])-x))


I receive the following error:



Error in `[.data.frame`(df, df$cluster == "A", x) : undefined columns selected 


Any help would be much appreciated!










share|improve this question

























  • I think the 4th value of x.var should be -3 (2-5) ?

    – thelatemail
    Jan 2 at 0:26











  • You are right. Thanks for catching that. I adjusted the value.

    – Jeff
    Jan 2 at 4:00














2












2








2








I am trying to create a list of new variables that represent the deviations from the minimum values of variables based on subsets of another variable.



Consider the following:



df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))


I would like to create two new variables, call them x.var and y.var, that take on the deviation from the minimum value of the respective underlying variables contingent on cluster. Thus, x.var and y.var would hopefully be:



x.var y.var
-1 -3
-3 -2
0 0
-3 0
0 -1
-5 -3


I have tried unsuccessfully to use lapply with an anonymous function to accomplish this:



vars <- lapply(df[,c(2:3)],function(x) 
ifelse(df$cluster=="A",
min(df[df$cluster=="A",x])-x,
min(df[df$cluster=="B",x])-x))


I receive the following error:



Error in `[.data.frame`(df, df$cluster == "A", x) : undefined columns selected 


Any help would be much appreciated!










share|improve this question
















I am trying to create a list of new variables that represent the deviations from the minimum values of variables based on subsets of another variable.



Consider the following:



df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))


I would like to create two new variables, call them x.var and y.var, that take on the deviation from the minimum value of the respective underlying variables contingent on cluster. Thus, x.var and y.var would hopefully be:



x.var y.var
-1 -3
-3 -2
0 0
-3 0
0 -1
-5 -3


I have tried unsuccessfully to use lapply with an anonymous function to accomplish this:



vars <- lapply(df[,c(2:3)],function(x) 
ifelse(df$cluster=="A",
min(df[df$cluster=="A",x])-x,
min(df[df$cluster=="B",x])-x))


I receive the following error:



Error in `[.data.frame`(df, df$cluster == "A", x) : undefined columns selected 


Any help would be much appreciated!







r list apply lapply






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 3:59







Jeff

















asked Jan 2 at 0:16









JeffJeff

135




135













  • I think the 4th value of x.var should be -3 (2-5) ?

    – thelatemail
    Jan 2 at 0:26











  • You are right. Thanks for catching that. I adjusted the value.

    – Jeff
    Jan 2 at 4:00



















  • I think the 4th value of x.var should be -3 (2-5) ?

    – thelatemail
    Jan 2 at 0:26











  • You are right. Thanks for catching that. I adjusted the value.

    – Jeff
    Jan 2 at 4:00

















I think the 4th value of x.var should be -3 (2-5) ?

– thelatemail
Jan 2 at 0:26





I think the 4th value of x.var should be -3 (2-5) ?

– thelatemail
Jan 2 at 0:26













You are right. Thanks for catching that. I adjusted the value.

– Jeff
Jan 2 at 4:00





You are right. Thanks for catching that. I adjusted the value.

– Jeff
Jan 2 at 4:00












2 Answers
2






active

oldest

votes


















0














Here is a base R method that uses ave with lapply. Loop through the columns of dataset excluding the 'cluster', then with ave get the min grouped by 'cluster', subtract from the column and assign the list of vectors to new columns



df[paste0(names(df)[-1], ".var")] <- lapply(df[-1], function(x)
ave(x, df$cluster, FUN = min) - x)
df
# cluster x y x.var y.var
#1 A 3 4 -1 -3
#2 B 4 5 -3 -2
#3 B 1 3 0 0
#4 A 5 1 -3 0
#5 A 2 2 0 -1
#6 B 6 6 -5 -3





share|improve this answer



















  • 1





    Thank you very much for the recommended approach. This is extremely helpful.

    – Jeff
    Jan 2 at 11:37



















1














Here's an approach using dplyr.



library(dplyr)

df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))

df %>%
group_by(cluster) %>%
mutate(x.var = min(x) - x,
y.var = min(y) - y)

#> # A tibble: 6 x 5
#> # Groups: cluster [2]
#> cluster x y x.var y.var
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 A 3 4 -1 -3
#> 2 B 4 5 -3 -2
#> 3 B 1 3 0 0
#> 4 A 5 1 -3 0
#> 5 A 2 2 0 -1
#> 6 B 6 6 -5 -3


Created on 2019-01-01 by the reprex package (v0.2.1)






share|improve this answer
























  • Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

    – Jeff
    Jan 2 at 4:02











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53999980%2fusing-lapply-to-create-new-variables-based-on-multiple-conditions-and-subsets%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Here is a base R method that uses ave with lapply. Loop through the columns of dataset excluding the 'cluster', then with ave get the min grouped by 'cluster', subtract from the column and assign the list of vectors to new columns



df[paste0(names(df)[-1], ".var")] <- lapply(df[-1], function(x)
ave(x, df$cluster, FUN = min) - x)
df
# cluster x y x.var y.var
#1 A 3 4 -1 -3
#2 B 4 5 -3 -2
#3 B 1 3 0 0
#4 A 5 1 -3 0
#5 A 2 2 0 -1
#6 B 6 6 -5 -3





share|improve this answer



















  • 1





    Thank you very much for the recommended approach. This is extremely helpful.

    – Jeff
    Jan 2 at 11:37
















0














Here is a base R method that uses ave with lapply. Loop through the columns of dataset excluding the 'cluster', then with ave get the min grouped by 'cluster', subtract from the column and assign the list of vectors to new columns



df[paste0(names(df)[-1], ".var")] <- lapply(df[-1], function(x)
ave(x, df$cluster, FUN = min) - x)
df
# cluster x y x.var y.var
#1 A 3 4 -1 -3
#2 B 4 5 -3 -2
#3 B 1 3 0 0
#4 A 5 1 -3 0
#5 A 2 2 0 -1
#6 B 6 6 -5 -3





share|improve this answer



















  • 1





    Thank you very much for the recommended approach. This is extremely helpful.

    – Jeff
    Jan 2 at 11:37














0












0








0







Here is a base R method that uses ave with lapply. Loop through the columns of dataset excluding the 'cluster', then with ave get the min grouped by 'cluster', subtract from the column and assign the list of vectors to new columns



df[paste0(names(df)[-1], ".var")] <- lapply(df[-1], function(x)
ave(x, df$cluster, FUN = min) - x)
df
# cluster x y x.var y.var
#1 A 3 4 -1 -3
#2 B 4 5 -3 -2
#3 B 1 3 0 0
#4 A 5 1 -3 0
#5 A 2 2 0 -1
#6 B 6 6 -5 -3





share|improve this answer













Here is a base R method that uses ave with lapply. Loop through the columns of dataset excluding the 'cluster', then with ave get the min grouped by 'cluster', subtract from the column and assign the list of vectors to new columns



df[paste0(names(df)[-1], ".var")] <- lapply(df[-1], function(x)
ave(x, df$cluster, FUN = min) - x)
df
# cluster x y x.var y.var
#1 A 3 4 -1 -3
#2 B 4 5 -3 -2
#3 B 1 3 0 0
#4 A 5 1 -3 0
#5 A 2 2 0 -1
#6 B 6 6 -5 -3






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 2 at 6:12









akrunakrun

415k13204278




415k13204278








  • 1





    Thank you very much for the recommended approach. This is extremely helpful.

    – Jeff
    Jan 2 at 11:37














  • 1





    Thank you very much for the recommended approach. This is extremely helpful.

    – Jeff
    Jan 2 at 11:37








1




1





Thank you very much for the recommended approach. This is extremely helpful.

– Jeff
Jan 2 at 11:37





Thank you very much for the recommended approach. This is extremely helpful.

– Jeff
Jan 2 at 11:37













1














Here's an approach using dplyr.



library(dplyr)

df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))

df %>%
group_by(cluster) %>%
mutate(x.var = min(x) - x,
y.var = min(y) - y)

#> # A tibble: 6 x 5
#> # Groups: cluster [2]
#> cluster x y x.var y.var
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 A 3 4 -1 -3
#> 2 B 4 5 -3 -2
#> 3 B 1 3 0 0
#> 4 A 5 1 -3 0
#> 5 A 2 2 0 -1
#> 6 B 6 6 -5 -3


Created on 2019-01-01 by the reprex package (v0.2.1)






share|improve this answer
























  • Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

    – Jeff
    Jan 2 at 4:02
















1














Here's an approach using dplyr.



library(dplyr)

df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))

df %>%
group_by(cluster) %>%
mutate(x.var = min(x) - x,
y.var = min(y) - y)

#> # A tibble: 6 x 5
#> # Groups: cluster [2]
#> cluster x y x.var y.var
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 A 3 4 -1 -3
#> 2 B 4 5 -3 -2
#> 3 B 1 3 0 0
#> 4 A 5 1 -3 0
#> 5 A 2 2 0 -1
#> 6 B 6 6 -5 -3


Created on 2019-01-01 by the reprex package (v0.2.1)






share|improve this answer
























  • Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

    – Jeff
    Jan 2 at 4:02














1












1








1







Here's an approach using dplyr.



library(dplyr)

df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))

df %>%
group_by(cluster) %>%
mutate(x.var = min(x) - x,
y.var = min(y) - y)

#> # A tibble: 6 x 5
#> # Groups: cluster [2]
#> cluster x y x.var y.var
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 A 3 4 -1 -3
#> 2 B 4 5 -3 -2
#> 3 B 1 3 0 0
#> 4 A 5 1 -3 0
#> 5 A 2 2 0 -1
#> 6 B 6 6 -5 -3


Created on 2019-01-01 by the reprex package (v0.2.1)






share|improve this answer













Here's an approach using dplyr.



library(dplyr)

df <- data.frame(
cluster = c("A","B","B","A","A","B"),
x = c(3,4,1,5,2,6),
y = c(4,5,3,1,2,6))

df %>%
group_by(cluster) %>%
mutate(x.var = min(x) - x,
y.var = min(y) - y)

#> # A tibble: 6 x 5
#> # Groups: cluster [2]
#> cluster x y x.var y.var
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 A 3 4 -1 -3
#> 2 B 4 5 -3 -2
#> 3 B 1 3 0 0
#> 4 A 5 1 -3 0
#> 5 A 2 2 0 -1
#> 6 B 6 6 -5 -3


Created on 2019-01-01 by the reprex package (v0.2.1)







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 2 at 0:39









Jake KauppJake Kaupp

5,70721428




5,70721428













  • Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

    – Jeff
    Jan 2 at 4:02



















  • Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

    – Jeff
    Jan 2 at 4:02

















Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

– Jeff
Jan 2 at 4:02





Hi Jake. Thanks a ton for the recommendation. This approach completely solves my inquiry.

– Jeff
Jan 2 at 4:02


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53999980%2fusing-lapply-to-create-new-variables-based-on-multiple-conditions-and-subsets%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

SQL update select statement

'app-layout' is not a known element: how to share Component with different Modules