R - 在包含字符串的字符数组中查找元素

时间:2013-11-01 16:31:46

标签: string r

我想提取包含某些特定字符串的字符数组的元素。例如:

x <- c('aa', 'ab', 'ac', 'bb', 'bc')

我想要一些函数,给定x'a'(通常这可以是一个字符串),它返回'aa', 'ab', 'ac'。我已尝试使用%in%matchwhich等组合,但未能使它们正常工作。有什么想法吗?

2 个答案:

答案 0 :(得分:42)

只需使用grep

grep('a', x, value=TRUE)
[1] "aa" "ab" "ac"

答案 1 :(得分:0)

在表或列表中,我们可以使用dplyr / tidyverse包中的dplyr :: pull将列中的值首先转换为向量,然后在列中查找特定值。例如,在乐高示例中,我们可以执行以下操作以找到以“ s”或“ S”开头的任何主题:

@IBDesignable
public class CircleProgress: UIView {

    @IBInspectable
    public var lineWidth: CGFloat = 5              { didSet { updatePath() } }

    @IBInspectable
    public var strokeEnd: CGFloat = 1              { didSet { progressLayer.strokeEnd = strokeEnd } }

    @IBInspectable
    public var trackColor: UIColor = .black        { didSet { trackLayer.strokeColor = trackColor.cgColor } }

    @IBInspectable
    public var progressColor: UIColor = .red       { didSet { progressLayer.strokeColor = progressColor.cgColor } }

    @IBInspectable
    public var inset: CGFloat = 0                  { didSet { updatePath() } }

    private lazy var trackLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.fillColor = UIColor.clear.cgColor
        layer.strokeColor = trackColor.cgColor
        layer.lineWidth = lineWidth
        return layer
    }()

    private lazy var progressLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.fillColor = UIColor.clear.cgColor
        layer.strokeColor = progressColor.cgColor
        layer.lineWidth = lineWidth
        return layer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }
}

private extension CircleProgress {
    func setupView() {
        layer.addSublayer(trackLayer)
        layer.addSublayer(progressLayer)
    }

    func updatePath() {
        let rect = bounds.insetBy(dx: lineWidth / 2 + inset, dy: lineWidth / 2 + inset)

        let centre = CGPoint(x: rect.midX, y: rect.midY)
        let radius = min(rect.width, rect.height) / 2
        let path = UIBezierPath(arcCenter: centre,
                                radius: radius,
                                startAngle: -.pi / 2,
                                endAngle: 3 * .pi / 2,
                                clockwise: true)

        trackLayer.path = path.cgPath
        trackLayer.lineWidth = lineWidth

        progressLayer.path = path.cgPath
        progressLayer.lineWidth = lineWidth
    }
}