How to use ifelse for specific column?

Hi. I have created the following in R

net<-data.frame(source=c("A","A","B","C","D","D","E"),target=c("B","D","A","A","C","E","D"))

library(igraph)
graph<-graph_from_data_frame(d=net,directed=TRUE)
plot(graph)
adj<-get.adjacency(graph,sparse=FALSE)

ifelse(adj[,c(1)]==1,x=sum(adj[,c(1)]-adj[c(1),],x=0))

I want to calculate this equation:

How do I do that? Thank you in advance!

Hi,

Welcome to the RStudio community!

The ifelse function does not wrap the whole statement, but just the columns you like to work on like this

adj[,c(1)] = ifelse(adj[,c(1)]==1, sum(adj[,c(1)]-adj[c(1),]),0)

All it does is take a vector of T/F, then returns values from two other vectors depending on the case. It's also possible to just return one value for either T or F, as you are doing here (the sum or 0).

Example:

# Vector input, one possible true of false answer
ifelse((1:5 %% 2) == 0, "even", "odd")
#> [1] "odd"  "even" "odd"  "even" "odd"

# Vector input, pick corresponding index value from true or false vectors
ifelse((1:5 %% 2) == 0, letters[1:5], LETTERS[1:5])
#> [1] "A" "b" "C" "d" "E"

Created on 2022-04-18 by the reprex package (v2.0.1)

My answer if just helping you fix your current error, but I'm not 100% sure if your code captures the function one you provided, so please check this.

Hope this helps,
PJ

Thank you sm! The solution you give does fix the error. Unfortunately, like you said, your code does not capture the function I provided. It's ok. I'll figure it out.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.